[英]Tweepy Hipchat API - Except rate limit?
我有以下代碼來獲取Twitter用戶的關注者:
followers=[]
for user in tweepy.Cursor(api.followers,id=uNameInput).items():
followers.append(user.screen_name)
但是,如果將其用於具有多個關注者的用戶,則腳本將獲得速率限制並停止。 我通常會把這說成真的。 嘗試,除了其他中斷循環,但不確定在這種情況下它將去哪里。
如果您想避免速率限制,則可以/應該等待下一個關注者頁面請求:
for user in tweepy.Cursor(api.followers, id=uNameInput).items():
followers.append(user.screen_name)
time.sleep(60)
看起來不漂亮,但應該有幫助。
UPD:根據官方的Twitter限制 ,您每15分鍾只能發送30個請求才能獲得followers
。
因此,您可以捕獲速率限制異常並等待15分鍾間隔結束,或者定義一個計數器並確保每15分鍾間隔不超過30個請求。
這是一個示例,說明如何捕獲蠕蟲異常並等待15分鍾,然后再轉到下一部分關注者:
import time
import tweepy
auth = tweepy.OAuthHandler(..., ...)
auth.set_access_token(..., ...)
api = tweepy.API(auth)
items = tweepy.Cursor(api.followers, screen_name="gvanrossum").items()
while True:
try:
item = next(items)
except tweepy.TweepError:
time.sleep(60 * 15)
item = next(items)
print item
雖然不確定這是最好的方法。
UPD2:還有另一個選項:您可以檢查rate_limit_status ,查看對followers
還有多少請求,然后決定等待還是繼續。
希望能有所幫助。
使用新的rate_limit_status的reset屬性,可以執行更精確的操作。 @alecxe的答案會迫使您每次等待15分鍾,即使窗口很小,您也可以等待適當的時間,而不必這樣做:
import time
import tweepy
import calendar
import datetime
auth = tweepy.OAuthHandler(..., ...)
auth.set_access_token(..., ...)
api = tweepy.API(auth)
items = tweepy.Cursor(api.followers, screen_name="gvanrossum").items()
while True:
try:
item = next(items)
except tweepy.TweepError:
#Rate limited. Checking when to try again
rate_info = api.rate_limit_status()['resources']
reset_time = rate_info['followers']['/followers/ids']['reset']
cur_time = calendar.timegm(datetime.datetime.utcnow().timetuple())
#wait the minimum time necessary plus a few seconds to be safe
try_again_time = reset_time - cur_time + 5
#Will try again in try_again_time seconds...
time.sleep(try_again_time)
這是我的代碼
try:
followers=[]
for user in tweepy.Cursor(api.followers,id=uNameInput).items():
followers.append(user.screen_name)
except:
errmsg = str(sys.exc_info()[1])
printdebug(errmsg)
if errmsg.find("'code': 88") != -1: # [{'message': 'Rate limit exceeded', 'code': 88}]
print("Blocked.")
time.sleep(60 * 60) # Wait 1 hour for unblock
pass
else:
raise
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.