Return the number of remaining hits tweepy

坚强是说给别人听的谎言 提交于 2019-12-24 21:35:25

问题


EDIT: I am trying the following code in order to read a list of ids and get their corresponant names. I am trying to use reamin_search_limits in order to avoid rate_limit errors.

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)+"\n")
         ss.write(str(user.name)+"\n")
except (tweepy.TweepError) as e:
    print e 
    stream.close()
    ss.close()

Everytime remain_search_limits is printed it return 180 until to get tweepError exception.


回答1:


This example shows you how to access how many tweets are remaining.

print rate_limit_json["resources"]["search"]['/search/tweets']['remaining']
180

"resources" is the key you should be using to access the information inside.

If you want to update the value, put it in a loop reassigning the value after your time.sleep().

Put all the code inside a while loop: Something like this:

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)

I have not tested the code but it should be close to what you need.

You may want to sleep between calls, I am unfamiliar with the api so not sure exactly what you are doing.



来源:https://stackoverflow.com/questions/23653432/return-the-number-of-remaining-hits-tweepy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!