不明白 Tweepy 错误



我只是得到python的窍门,我想开始使用它与API等。我安装了Tweepy,拿到了我的Twitter密钥,然后在他们的网站上进行了设置。一切都很好,直到,嗯,这里

import tweepy
auth = tweepy.OAuthHandler('qwertyuiop', 'asdfghjkl')
auth.set_access_token('qazsecftgbhujmkolp', 'plokmjuhbgtfcdeszaq')
api = tweepy.API(auth)
user = tweepy.api.get_user('twitter')
print user.screen_name

(当然是用我真正的钥匙)

返回错误

Traceback (most recent call last):
  File "tweeter.py", line 8, in <module>
    user = tweepy.api.get_user('twitter')
  File "/home/jeremiah/.local/lib/python2.7/site-packages/tweepy/binder.py", line 243, in _call
    return method.execute()
  File "/home/jeremiah/.local/lib/python2.7/site-packages/tweepy/binder.py", line 189, in execute
    raise TweepError('Failed to send request: %s' % e)
tweepy.error.TweepError: Failed to send request: local variable 'auth' referenced before assignment

我就是不明白。定义auth是我要做的第一件事。此外,这是从网站的入门课程中直接取下来的。

看起来一切都很好,直到user = tweepy.api.get_user('twitter')。如果我把下面的+去掉,没问题,或者我用

代替
public_tweets = api.home_timeline()
for tweet in public_tweets:
    print tweet.text

没关系。

那是什么呢?是Tweepy坏了,还是我的电脑坏了,还是我错过了什么明显的东西?

感谢您的帮助

您应该能够使用tweepy.API类的get_user方法(您已经将其分配给变量名称api)。

试题:

user = api.get_user(id='__your__username__')  # returns the user specified by id

或:

user = api.me()  # returns YOUR authenticated user object
您需要在括号中指定您的用户名,或者使用me()方法(而不是文字'twitter'(它从@twitter返回用户对象,因为您已经要求它获取那个用户!)的原因是get_user方法:

返回指定用户的信息。

参数:
id -指定用户的id或屏幕名。

user_id -用户ID。当一个有效的用户ID也是一个有效的屏幕名时,有助于消除歧义。

screen_name -指定用户的屏幕名称。当有效的屏幕名也是用户ID时,有助于消除歧义。

关于你的代码,注意下面的区别,这会引发一个异常:

user = tweepy.api.get_user('twitter'). 

和this,它不会引发异常

public_tweets = api.home_timeline()   '## NOT tweepy.api.home_timeline()

在后者(它不会出错)中,您正确地使用api变量来调用home_timeline方法。

相关内容

最新更新