返回剩余的Tweepy点击数
问题描述
编辑:我正在尝试以下代码,以便读取ID列表并获取它们的对应名称。我正在尝试使用reamin_search_limits,以避免Rate_Limit错误。
limits = api.rate_limit_status()
remain_search_limits = limits['resources']['search']['/search/tweets']['remaining']
stream = open('myfile','w')
ss = open('userNames', 'w')
for ids in content:
try:
limits = api.rate_limit_status()
remain_search_limits = limits['resources']['search']['/search/tweets']['remaining']
print 'you have', remain_search_limits, 'API calls remaining until next hour'
if remain_search_limits < 2:
dtcode = datetime.utcnow()
unixtime = calendar.timegm(dtcode.utctimetuple())
sleeptime = rate_limit_json.get('reset_time_in_seconds') - unixtime + 10
print 'waiting ', sleeptime, 'seconds'
sleep(sleeptime)
else:
user = api.get_user(ids)
stream.write(str(user.id)+"
")
ss.write(str(user.name)+"
")
except (tweepy.TweepError) as e:
print e
stream.close()
ss.close()
每次打印RESTAIN_SEARCH_LIMITS时返回180,直到出现tweepError异常。
解决方案
此示例显示如何访问剩余的tweet数量。
print rate_limit_json["resources"]["search"]['/search/tweets']['remaining']
180
"resources" is the key you should be using to access the information inside.
如果您要更新值,请将其放入循环中,并在计时后重新赋值。睡眠()。
将所有代码放在一个While循环中: 大概是这样的:limits = api.rate_limit_status()
remain_search_limits = limits['resources']['search']['/search/tweets']['remaining']
while remain_search_limits >2:
limits = api.rate_limit_status()
remain_search_limits = limits['resources']['search']['/search/tweets']['remaining']
else:
dtcode = datetime.utcnow()
unixtime = calendar.timegm(dtcode.utctimetuple())
sleeptime = rate_limit_json.get('reset_time_in_seconds') - unixtime + 10
print 'waiting ', sleeptime, 'seconds'
sleep(sleeptime)
我尚未测试代码,但它应该接近您需要的内容。
您可能希望在两次调用之间休眠,我不熟悉该API,因此不确定您到底在做什么。
相关文章