我正在尝试使用Tweepy检索Twitter数据,使用下面的代码,但它返回401错误,我重新生成了访问权限和秘密令牌,但没有产生任何影响
#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 = "ENTER YOUR ACCESS TOKEN"
access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET"
consumer_key = "ENTER YOUR API KEY"
consumer_secret = "ENTER YOUR API SECRET"
#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'])
代码可用here
我知道代码中的所有其他内容都是正确的,并且没有语法或身份验证错误。我在question的答案中读到401错误也是因为服务器 - 客户端的时间差异。
我的问题是:我应该如何设置系统时间来克服此错误?或者换句话说,我怎么知道服务器时间以便改变我的系统时间?
答案 0 :(得分:0)
当您向Twitter API服务器发送HTTP请求时,它会发回一个响应。您应捕获响应标头,其中包括服务器时间,如下所示:
HTTP/1.1 200 OK
cache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
content-encoding: gzip
content-length: 128
content-security-policy: default-src 'none'; connect-src 'self'; font-src https://abs.twimg.com https://abs-0.twimg.com data:; frame-src 'self' twitter:; img-src https://abs.twimg.com https://*.twimg.com https://pbs.twimg.com data:; media-src 'none'; object-src 'none'; script-src https://abs.twimg.com https://abs-0.twimg.com https://twitter.com https://mobile.twitter.com; style-src https://abs.twimg.com https://abs-0.twimg.com; report-uri https://twitter.com/i/csp_report?a=NVQWGYLXFVWG6Z3JNY%3D%3D%3D%3D%3D%3D&ro=false;
content-type: text/html;charset=utf-8
date: Fri, 23 Mar 2018 22:07:58 GMT
expires: Tue, 31 Mar 1981 05:00:00 GMT
last-modified: Fri, 23 Mar 2018 22:07:58 GMT
ml: S
pragma: no-cache
server: tsa_a
set-cookie: personalization_id="v1_nP/EL/R5y9o+PHvzC1MJ+Q=="; Expires=Sun, 22 Mar 2020 22:07:58 UTC; Path=/; Domain=.twitter.com
set-cookie: guest_id=v1%3A152184287871578374; Expires=Sun, 22 Mar 2020 22:07:58 UTC; Path=/; Domain=.twitter.com
status: 200 OK
strict-transport-security: max-age=631138519
x-connection-hash: 2845e4d99e8f17d11e186a489c475414
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-response-time: 83
x-transaction: 003e14470092d818
x-twitter-response-tags: BouncerCompliant
x-ua-compatible: IE=edge,chrome=1
x-xss-protection: 1; mode=block; report=https://twitter.com/i/xss_report
注意date
标题:
date: Fri, 23 Mar 2018 22:07:58 GMT
它使用GMT,因此如果您的服务器设置为不同的时区,请调整时差。
我使用Fiddler并从OAuth请求令牌(https://api.twitter.com/oauth/request_token)端点获得此响应 - 因此,您无需获得授权,然后才能执行此操作。