我刚刚掌握了 python 的窍门,我想开始将它与 API 等一起使用。我安装了 Tweepy,获得了我的 Twitter key ,并按照他们网站上的设置过程进行操作。一切都很好,直到,好吧,这里
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
(当然是用我的真 key )
返回错误
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 是我做的第一件事。此外,这是从网站的介绍类(class)中直接摘录的。
在 user = tweepy.api.get_user('twitter') 之前似乎一切正常。如果我把它 + 下面的所有东西都去掉,那很好,或者如果我用
public_tweets = api.home_timeline()
for tweet in public_tweets:
print tweet.text
没关系。
那是什么? Tweepy 有问题吗?我的电脑有问题吗?还是我只是漏掉了一些明显的东西?
感谢您的帮助
请您参考如下方法:
您应该能够使用 tweepy.API class 的 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 method :
Returns information about the specified user.
Parameters:
id – Specifies the ID or screen name of the user.user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
关于您的代码,请注意两者之间的区别,这会引发异常:
user = tweepy.api.get_user('twitter').
还有这个,它不会引发异常
public_tweets = api.home_timeline() '## NOT tweepy.api.home_timeline()
在后者(不会出错)中,您正确地使用了 api 变量来调用 home_timeline 方法。
