2016-09-21 66 views
0

我想湊使用Tweepy一些微博,但有以下錯誤幾百請求後,連接崩潰: tweepy.error.TweepError: 無法發送請求:('連接異常中止。 」,錯誤( 「(104, 'ECONNRESET')」,))Tweepy錯誤104:連接異常中止

我的代碼是這樣的:

for status in tweepy.Cursor(api.search, 
          q="", 
          count=100, 
          include_entities=True, 
          monitor_rate_limit=True, 
          wait_on_rate_limit=True, 
          wait_on_rate_limit_notify = True, 
          retry_count = 5, #retry 5 times 
          retry_delay = 5, #seconds to wait for retry 
          geocode ="34.0207489,-118.6926066,100mi", # los angeles 
          until=until_date, 
          lang="en").items(): 

     try: 
     towrite = json.dumps(status._json) 
     output.write(towrite + "\n") 
     except Exception, e: 
     log.error(e) 
     c+=1 
     if c % 10000 == 0: # 100 requests, sleep 
     time.sleep(900) # sleep 15 min 

我可以嘗試/捕獲錯誤除外,但我不能重啓光標從它墜毀的地方開始。 有誰知道如何解決這個錯誤,或重新從最後一個已知的狀態光標?

謝謝!

回答

1

Tweepy文檔顯示,請求/ 15分鐘窗口(用戶身份驗證)爲180,但顯然睡眠時間太長會影響連接可靠性(在某些請求後),所以如果每5秒運行一次請求,精細:

for status in tweepy.Cursor(api.search, 
         q="", 
         count=100, 
         include_entities=True, 
         monitor_rate_limit=True, 
         wait_on_rate_limit=True, 
         wait_on_rate_limit_notify = True, 
         retry_count = 5, #retry 5 times 
         retry_delay = 5, #seconds to wait for retry 
         geocode ="34.0207489,-118.6926066,100mi", # los angeles 
         until=until_date, 
         lang="en").items(): 

    try: 
    towrite = json.dumps(status._json) 
    output.write(towrite + "\n") 
    except Exception, e: 
    log.error(e) 
    c+=1 
    if c % 100 == 0: # first request completed, sleep 5 sec 
    time.sleep(5) 
0

在我看來,該tweepy調用應該是try塊內。此外,您在api.search中有不在Tweepy API中的參數(http://docs.tweepy.org/en/v3.5.0/api.html#help-methods)。無論如何,這對我有效:

backoff_counter = 1 
while True: 
    try: 
     for my_item in tweepy.Cursor(api.search, q="test").items(): 
      # do something with my_item 
     break 
    except tweepy.TweepError as e: 
     print(e.reason) 
     sleep(60*backoff_counter) 
     backoff_counter += 1 
     continue 

基本上,當你得到錯誤,你睡了一會兒,然後再試一次。我使用增量退避來確保休眠時間足以重新建立連接。

相關問題