【发布时间】:2019-06-18 15:40:39
【问题描述】:
我正在收集来自 Twitter 的 API 的回复来构建数据集的推文,我在 python 中使用 tweepy 库来实现这一点,但问题是我经常遇到这个错误(达到了速率限制。正在睡觉:(任何数字(秒))都会延迟我,我必须在最短的时间内收集尽可能多的数据
我读到 twitter 的速率限制是我认为每 15 分钟 15 个请求或类似的东西,但在我的情况下,我只能收集一条或两条推文,直到它再次停止,有时它会停止 15 分钟然后再次停止 15 分钟,没有给我时间,我不知道是什么导致了问题,不管是不是我的代码?
# Import the necessary package to process data in JSON format
try:
import json
except ImportError:
import simplejson as json
# Import the tweepy library
import tweepy
import sys
# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = '-'
ACCESS_SECRET = '-'
CONSUMER_KEY = '-'
CONSUMER_SECRET = '-'
# Setup tweepy to authenticate with Twitter credentials:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
# Create the api to connect to twitter with your creadentials
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)
file2 = open('replies.csv','w', encoding='utf-8-sig')
replies=[]
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
for full_tweets in tweepy.Cursor(api.search,q='#عربي',timeout=999999,tweet_mode='extended').items():
if (not full_tweets.retweeted) and ('RT @' not in full_tweets.full_text):
for tweet in tweepy.Cursor(api.search,q='to:'+full_tweets.user.screen_name,result_type='recent',timeout=999999,tweet_mode='extended').items(1000):
if hasattr(tweet, 'in_reply_to_status_id_str'):
if (tweet.in_reply_to_status_id_str==full_tweets.id_str):
replies.append(tweet.full_text)
print(full_tweets._json)
file2.write("{ 'id' : "+ full_tweets.id_str + "," +"'Replies' : ")
for elements in replies:
file2.write(elements.strip('\n')+" , ")
file2.write("}\n")
replies.clear()
file2.close()
$ python code.py > file.csv
Rate limit reached. Sleeping for: 262
Rate limit reached. Sleeping for: 853
【问题讨论】:
-
多个嵌套的
for-if-for-if循环遍历 Twitter api 返回的 所有 推文,所以即使你的if-statements 返回False,你已经到达处理查询中的 15 个请求后的速率限制。通过检查每个tweepy.Cursor()请求的长度并查看它是否包含超过 15 个查询,您可以找到导致速率限制的循环。