亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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條經驗 獲得超6個贊

在文檔的代碼片段部分下有一個示例,建議使用包裝函數來處理錯誤處理。


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 關注
  • 247 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號