【问题标题】:Understanding raise RemoteDisconnected("Remote end closed connection"了解 raise RemoteDisconnected("远程结束关闭连接"
【发布时间】:2018-12-27 01:06:39
【问题描述】:

我正在抓取 twitter,试图让被关注的朋友/用户获取 twitter 用户列表。我在 OSX 10.13 上使用 tweepy 和 python 3.6.5。缩写代码块:

def get_friends_for_each_twitter_user(UserL=None, Name=None):
   .
   . # Auth keys and such
   .
   for user in UserL:  ### This is a list of USER class with the below fields ###
        ### Handle protected users ###
        if(user.protected == True):
            user.friendsL = "protected"
            continue
        screenNameL=[]
        friendIDL=[]
        friendL=[]
        friendScreenNameL=[]
        ### Get IDs of people that this user follows (i.e. 'friends') ###
        for page in tweepy.Cursor(api.friends_ids, screen_name=user.screenName).pages():
            friendIDL.extend(page)
            time.sleep(60)
        ## Loop through IDs, get user profile, keep only friends' screen name ###
        for i in range(0, len(friendIDL), 100):
            friendL.extend(api.lookup_users(user_ids=friendIDL[i:i+100]))
        ### Keep only screen name ###
        for friend in friendL:
            friendScreenNameL.append(friend._json['screen_name'])
        user.friendsL = friendScreenNameL

当我这样做时,在收集了大约十几个用户的 friends(即用户关注的个人资料)后,我收到以下错误:

Traceback (most recent call last):
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 387, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 383, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1331, in getresponse
    response.begin()
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 266, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/requests/adapters.py", line 440, in send
    timeout=timeout
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/util/retry.py", line 357, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/packages/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 387, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 383, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1331, in getresponse
    response.begin()
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 266, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/tweepy/binder.py", line 190, in execute
    proxies=self.api.proxy)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/requests/adapters.py", line 490, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pdb.py", line 1667, in main
    pdb._runscript(mainpyfile)
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pdb.py", line 1548, in _runscript
    self.run(statement)
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/bdb.py", line 434, in run
    exec(cmd, globals, locals)
  File "<string>", line 1, in <module>
  File "/Users/myusername/Code/Python/hair_prod/src/main.py", line 170, in <module>
    main()
  File "/Users/myusername/Code/Python/hair_prod/src/main.py", line 141, in main
    get_friends_for_each_twitter_user(UserL=tresemmeUserL, Name="Tresemme")
  File "src/twitter_scraper.py", line 187, in get_friends_for_each_twitter_user
    friendL.extend(api.lookup_users(user_ids=friendIDL[i:i+100]))
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/tweepy/api.py", line 336, in lookup_users
    return self._lookup_users(post_data=post_data)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/tweepy/binder.py", line 250, in _call
    return method.execute()
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/tweepy/binder.py", line 192, in execute
    six.reraise(TweepError, TweepError('Failed to send request: %s' % e), sys.exc_info()[2])
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/six.py", line 692, in reraise
    raise value.with_traceback(tb)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/tweepy/binder.py", line 190, in execute
    proxies=self.api.proxy)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/requests/adapters.py", line 490, in send
    raise ConnectionError(err, request=request)
tweepy.error.TweepError: Failed to send request: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/requests/adapters.py(490)send()
-> raise ConnectionError(err, request=request)

似乎错误发生在第 friendL.extend(api.lookup_users(user_ids=friendIDL[i:i+100])) 行的 get_friends_for_each_twitter_user()函数

问题

  1. 为什么会出现这个错误?

  2. 如何避免/解决它?

【问题讨论】:

标签: python python-3.x tweepy


【解决方案1】:

任何数量的事情都可能导致错误出现,但如果原因不是永久性的,那么重试偶尔失败的 API 调用可以使脚本正常工作。

根据Tweepy docs,API 客户端构造函数接受默认为 0 的retry_count 参数。尝试将retry_count 设置为大于 0 的值,看看您的脚本是否能够成功完成,如下所示:

api = tweepy.api.API(..., retry_count=3)

【讨论】:

    【解决方案2】:

    搞砸了一段时间后,我认为这个问题是由我的网络连接引起的。发生这种情况时,我已连接到我的 5GHz 无线网络。当我连接到我的 2.4GHz 无线网络时,这些错误就不那么频繁了。在这种情况下,正确的做法是处理异常,等待几秒钟,然后重试。下面是相应的代码片段:

    def get_friends_for_each_twitter_user(UserL=None, Name=None):
        consumerKey =  #your value here
        consumerSecret = #your value here
        auth = tweepy.AppAuthHandler(consumerKey, consumerSecret)  ### Supposedly faster
        api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)  ## Now I don't have to handle rate limiting myself
    
        for user in UserL:
            accountStatus = 'active'
            if(user.protected == True):
                user.friendsL = "protected"
                continue
            screenNameL=[]
            friendIDL=[]
            friendL=[]
            friendScreenNameL=[]
            #### TWITTER LIMITS US #####
            try :
                for page in tweepy.Cursor(api.friends_ids, screen_name=user.screenName).pages():
                    friendIDL.extend(page)
            except tweepy.TweepError as error :
                if(error.__dict__['api_code'] == 34):
                    accountStatus = 'dead'
                    print("...{} is dead".format(user.screenName))
                    continue
                else:
                    raise
    
            for i in range(0, len(friendIDL), 100):
                ### This handles when exception occurs (probably due to connection issues)
                ### When exception occurs, sleeps then retries. I don't notice this error
                ### when I'm running on corporate Wifi, maybe my router just sucks
                while True:
                    try :
                        friendL.extend(api.lookup_users(user_ids=friendIDL[i:i+100]))
                    except tweepy.TweepError as error :
                        print("...Exception for {} : api_code {}".format(user.screenName,
                              error.__dict__['api_code']))
                        time.sleep(5)
                        continue
                    break
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2021-08-20
      • 2023-01-10
      • 2017-03-12
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多