为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

函数式编程 2022-06-02 16:28:01
在使用 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在处理速率限制问题的同时迭代所有关注者的正确方法是什么?
查看完整描述

2 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

在文档的代码片段部分下有一个示例,建议使用包装函数来处理错误处理。


def limit_handled(cursor):

    while True:

        try:

            yield next(cursor)

        except tweepy.RateLimitError:

            time.sleep(15 * 60)

        except StopIteration:

            print("Done")

            break



for 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 调用。


查看完整回答
反对 回复 2022-06-02
?
慕沐林林

TA贡献2016条经验 获得超9个赞

您可以在变量上构造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


查看完整回答
反对 回复 2022-06-02
  • 2 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信