401使用Tweepy检索Twitter数据时出错



我正试图使用Tweepy,使用下面的代码检索Twitter数据,但我返回401错误,我重新生成了访问和秘密令牌,出现了相同的错误。

#imports
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
#setting up the keys
consumer_key = 'xxxxxxx'
consumer_secret = 'xxxxxxxx' 
access_token = 'xxxxxxxxxx'
access_secret = 'xxxxxxxxxxxxx'
class TweetListener(StreamListener):
# A listener handles tweets are the received from the stream.
#This is a basic listener that just prints received tweets to standard output
   def on_data(self, data):
       print (data)
       return True
   def on_error(self, status):
       print (status)

#printing all the tweets to the standard output
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

stream = Stream(auth, TweetListener())
t = u"#سوريا"
stream.filter(track=[t])

只需重置系统时钟即可。

如果API身份验证请求来自声称其时间超出了Twitter时间15分钟的服务器,则该请求将失败,并返回401错误。

ThankYou

您可能只是在从apps.twitter.com页面复制访问令牌时犯了一个错误。

您需要复制作为Access Token提供的全部内容,而不仅仅是-之后的字符串。

例如,复制并粘贴整个字符串,如74376347-jkghdui456hjkbjhgbm45gj,而不仅仅是jkghdui456hjkbjhgbm45gj

[注意,上面的字符串只是我出于演示目的随机键入的。不过,您的实际访问令牌也会是这样的,即,"数字字符串字母数字字符串"]

您只需要将键显示在双引号中并且您不必在上次twitter身份验证中定义您的密钥。

#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = 'X3YIzD'
access_token_secret = 'PiwPirr'
consumer_key = 'ekaOmyGn'
consumer_secret = 'RkFXRIOf83r'

#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
    print data
    return True
def on_error(self, status):
    print status

if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter 
Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'python', 
'javascript', 'ruby'
stream.filter(track=['python', 'javascript', 'ruby'])

我遇到了同样的问题-这里没有解决它。对我来说,使用Tweepy流式传输推文显然需要1A身份验证,而不是2A(请参阅-https://github.com/tweepy/tweepy/issues/1346)。这意味着您需要在身份验证对象中使用访问令牌和使用者令牌。

import tweepy
# user credentials
access_token = '...'
access_token_secret = '...'
consumer_key = '...'
consumer_secret = '...'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# this is the main difference
auth.set_access_token(access_token, access_token_secret)
stream = tweepy.Stream(auth, tweepy.StreamListener)

在我的情况下,出现错误是因为我使用的是AppAuthHandler而不是OAuthHandler。切换到OAuthHandler解决了此问题。

在我的案例中,我遇到了这个问题,但这与时间无关。

我的应用程序有一个";只读";准许我不得不把它改成";读写";允许停止错误。

你可以通过去";"用户认证";在应用程序设置页面中。

更改只读权限后,必须重新生成访问令牌,然后将其放入代码中。谢谢你的帮助!

最新更新