在 tweepy 中使用 Cursor 处理速率限制异常

在使用 Cursor 对象遍历关注者列表时,我试图找到处理速率限制的正确方法。这是我正在尝试的:


while True:

    try:

        for follower in tweepy.Cursor(api.followers, id=root_usr).items():

            print(follower.id)

    except tweepy.TweepError:

        # hit rate limit, sleep for 15 minutes

        print('Rate limited. Sleeping for 15 minutes.')

        time.sleep(15 * 60 + 15)

        continue

    except StopIteration:

        break

这可能是不正确的,因为异常会使for循环重新从头开始。root_usr在处理速率限制问题的同时迭代所有关注者的正确方法是什么?


函数式编程
浏览 262回答 2
2回答

杨魅力

在文档的代码片段部分下有一个示例,建议使用包装函数来处理错误处理。def limit_handled(cursor):    while True:        try:            yield next(cursor)        except tweepy.RateLimitError:            time.sleep(15 * 60)        except StopIteration:            print("Done")            breakfor follower in limit_handled(tweepy.Cursor(api.followers, id=root_usr).items()):    print(follower.id)另外,我建议将 count 设置为最大值,tweepy.Cursor(api.followers, id=root_usr, count=200).items()以充分利用每个 API 调用。

慕沐林林

您可以在变量上构造Cursor实例并next(cursor)在 try-catch 中调用。您可以这样处理 StopIteration 和 TweepError。喜欢cursor = tweepy.Cursor(api.followers, id=root_usr).items()# or tweepy.Cursor(api.followers, id=root_usr).items().iter()while True:    try:        follower = next(cursor)        print(follower.id)    except StopIteration:        break    except tweepy.TweepError:        # Handle this, sleep, log, etc.        pass
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python