繁体   English   中英

在Python的Twython中适应Twitter的速率限制

[英]Accommodating Twitter's rate limit in Python's Twython

我正在使用Twython通过Twitter的REST API提取数据。 我希望代码在达到Twitter速率限制时会根据需要自动休息,然后再次开始查询。

这是代码,其中包含Twitter ID列表,并将其关注者ID添加到列表中:

for user in first_ids:
    try:
        followers = twitter.get_followers_ids(user_id=user, count=600)
        for individual in followers['ids']:    
            if individual not in ids:
                ids.append(individual)
    except TwythonRateLimitError as error:
        remainder = float(twitter.get_lastfunction_header(header='x-rate-limit-reset')) - time.time()
        time.sleep(remainder)
        continue

运行它时,出现以下错误:“连接异常终止。错误10054:远程主机强行关闭了现有连接”

错误是什么意思? 我想这与Twitter的速率限制有关-是否还有其他方法可以解决?

您在程序进入睡眠状态时保持连接打开状态,请尝试手动将其关闭,然后在睡眠超时后重新连接。 就像是:

    except TwythonRateLimitError as error:
        remainder = float(twitter.get_lastfunction_header(header='x-rate-limit-reset')) - time.time()
        twitter.disconnect()
        time.sleep(remainder)
        twitter = Twython(APP_KEY, APP_SECRET,OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        continue

如果您使用的是REST API,则可以使用相同的解决方案删除该API,而不是使用.disconnect(),只需使用

del twitter

代替

twitter.disconnect()

我有同样的问题,对我有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM