【问题标题】:Rate limit reached. Sleeping for:已达到速率限制。睡觉:
【发布时间】: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 个查询,您可以找到导致速率限制的循环。

标签: python tweepy


【解决方案1】:

希望这可能会有所帮助

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=False, compression=True)

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

只需将此行添加到 Python 脚本即可避免休眠:

sleep_on_rate_limit=False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2020-06-09
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多