2016-09-21 69 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 

基本上,当你得到错误,你睡了一会儿,然后再试一次。我使用增量退避来确保休眠时间足以重新建立连接。

相关问题