Python Tweepy Hipchat API-除了速率限制?

Python Tweepy Hipchat API-除了速率限制?,python,twitter,tweepy,Python,Twitter,Tweepy,我有以下代码来获取twitter用户的关注者: followers=[] for user in tweepy.Cursor(api.followers,id=uNameInput).items(): followers.append(user.screen_name) 但是,如果在具有多个跟随者的用户上使用此选项,则脚本将获得速率限制并停止。我通常会在一段时间内把这句话说成是真的;请尝试,除此之外,请中断循环,但不确定在这种情况下循环将转到何处。如果要避免速率限制,您可以/应该在下一

我有以下代码来获取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:根据这位官员的说法,你每15分钟只能发出30个请求来获得
追随者

所以,您可以捕获速率限制异常并等待15分钟间隔结束,或者定义一个计数器并确保每15分钟间隔发出的请求不超过30个

下面是一个示例,您如何捕获tweepy异常并等待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\u limit\u 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

问题是,不管发生什么,它都会等待。因此,如果在一个追随者很少的人身上使用,它将在处理数据之前等待一分钟。感谢这一点,计数器选项对我来说似乎有点粗略,我更愿意抓住利率限制,然后等待。问题是我不知道该把它放在哪里。我需要扩展循环吗?@Martyn,我添加了一个代码示例和另一个选项(请参见
UPD2
),非常感谢。你的while循环需要中断吗?@Martyn,是的,当然,你最终需要退出循环:)