2016-10-07 77 views
0

我試圖通過Python來訪問API(SCOPUS),內下載多個摘要for循環如下:錯誤處理當訪問API

for t in eid: 
    url = "http://api.elsevier.com/content/abstract/eid/"+str(t)+"?view=FULL" 
    # url = "http://api.elsevier.com/content/abstract/eid/2-s2.0-84934272190?view=FULL" 
    resp2 = requests.get(url, 
         headers={'Accept':'application/json', 
         'X-ELS-APIKey': MYAPIKEY}) 

    retrieval = resp2.json() 

    dep = retrieval['abstracts-retrieval-response']['item']['bibrecord']['head']['author-group'] 
    sub = retrieval['abstracts-retrieval-response']['subject-areas']['subject-area'] 
    iD = retrieval['abstracts-retrieval-response']['coredata']['intid'] 
    date = retrieval['abstracts-retrieval-response']['coredata']['prism:coverDate'] 

    department.append(dep) 
    subj.append(sub) 
    ident.append(iD) 
    dates.append(date) 

然而,在這方面,我不斷收到沿着以下錯誤下面的行(總是在for循環的不同點)。 我被告知錯誤處理是解決這個問題的一種方法,但對Python來說是新手,我不知道這是什麼。誰能幫忙?由於

編輯:這裏是

Traceback (most recent call last): 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 142, in _new_conn 
    (self.host, self.port), self.timeout, **extra_kw) 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py", line 91, in create_connection 
    raise err 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py", line 81, in create_connection 
    sock.connect(sa) 
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 578, in urlopen 
    chunked=chunked) 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 362, in _make_request 
    conn.request(method, url, **httplib_request_kw) 
    File "C:\Users\User\Anaconda3\lib\http\client.py", line 1106, in request 
    self._send_request(method, url, body, headers) 
    File "C:\Users\User\Anaconda3\lib\http\client.py", line 1151, in _send_request 
    self.endheaders(body) 
    File "C:\Users\User\Anaconda3\lib\http\client.py", line 1102, in endheaders 
    self._send_output(message_body) 
    File "C:\Users\User\Anaconda3\lib\http\client.py", line 934, in _send_output 
    self.send(msg) 
    File "C:\Users\User\Anaconda3\lib\http\client.py", line 877, in send 
    self.connect() 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 167, in connect 
    conn = self._new_conn() 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 151, in _new_conn 
    self, "Failed to establish a new connection: %s" % e) 
requests.packages.urllib3.exceptions.NewConnectionError: <requests.packages.urllib3.connection.HTTPConnection object at 0x000002058C7E1C18>: Failed to establish a new connection: [WinError 10053] An established connection was aborted by the software in your host machine 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\adapters.py", line 403, in send 
    timeout=timeout 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 623, in urlopen 
    _stacktrace=sys.exc_info()[2]) 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\util\retry.py", line 281, in increment 
    raise MaxRetryError(_pool, url, error or ResponseError(cause)) 
requests.packages.urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='api.elsevier.com', port=80): Max retries exceeded with url: /content/abstract/eid/2-s2.0-84978766692?view=FULL (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x000002058C7E1C18>: Failed to establish a new connection: [WinError 10053] An established connection was aborted by the software in your host machine',)) 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "<stdin>", line 5, in <module> 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\api.py", line 71, in get 
    return request('get', url, params=params, **kwargs) 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\api.py", line 57, in request 
    return session.request(method=method, url=url, **kwargs) 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\sessions.py", line 475, in request 
    resp = self.send(prep, **send_kwargs) 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\sessions.py", line 585, in send 
    r = adapter.send(request, **kwargs) 
    File "C:\Users\User\Anaconda3\lib\site-packages\requests\adapters.py", line 467, in send 
    raise ConnectionError(e, request=request) 
requests.exceptions.ConnectionError: HTTPConnectionPool(host='api.elsevier.com', port=80): Max retries exceeded with url: /content/abstract/eid/2-s2.0-84978766692?view=FULL (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x000002058C7E1C18>: Failed to establish a new connection: [WinError 10053] An established connection was aborted by the software in your host machine',)) 

回答

0

不幸的是,你還沒有包括在被提到「上述例外」整個的錯誤信息,應該包括所有的正確信息(抱歉,這是長)你的輸出。

但是,通常情況下,如果在執行一段代碼時發生異常情況(例如錯誤),則可以捕獲該異常並處理該異常。有一個例外是有關船上信息的對象。一般情況下的例外處理是一個很大的問題,您可能會從以下位置開始閱讀:https://docs.python.org/3/tutorial/errors.html

處理例外的示例只是報告環境和異常。這已經可以讓您瞭解在什麼地方出了錯:

for t in eid: 
    try: 
     url = "http://api.elsevier.com/content/abstract/eid/"+str(t)+"?view=FULL" 
     # url = "http://api.elsevier.com/content/abstract/eid/2-s2.0-84934272190?view=FULL" 
     resp2 = requests.get(url, 
          headers={'Accept':'application/json', 
          'X-ELS-APIKey': MYAPIKEY}) 

     retrieval = resp2.json() 

     dep = retrieval['abstracts-retrieval-response']['item']['bibrecord']['head']['author-group'] 
     sub = retrieval['abstracts-retrieval-response']['subject-areas']['subject-area'] 
     iD = retrieval['abstracts-retrieval-response']['coredata']['intid'] 
     date = retrieval['abstracts-retrieval-response']['coredata']['prism:coverDate'] 

     department.append(dep) 
     subj.append(sub) 
     ident.append(iD) 
     dates.append(date) 
    except Exception as exception: 
     print (url) # 'print' will only work on a console 
     print (exception) 

[編輯]

我在錯誤信息採取一看,好像是你試圖連接到服務器,關閉連接。儘管原因可能完全不同,但請參閱Why is host aborting connection?。試試上面的代碼,找出如果這一切發生的時間或僅與特定的URL

[/編輯]

要建立在一些重試,使用:

import time 

nrOfTries = 10 

for t in eid: 
    for count in range (nrOfTries): 
     try: 
      url = "http://api.elsevier.com/content/abstract/eid/"+str(t)+"?view=FULL" 
      # url = "http://api.elsevier.com/content/abstract/eid/2-s2.0-84934272190?view=FULL" 
      resp2 = requests.get(url, 
           headers={'Accept':'application/json', 
           'X-ELS-APIKey': MYAPIKEY}) 

      retrieval = resp2.json() 

      dep = retrieval['abstracts-retrieval-response']['item']['bibrecord']['head']['author-group'] 
      sub = retrieval['abstracts-retrieval-response']['subject-areas']['subject-area'] 
      iD = retrieval['abstracts-retrieval-response']['coredata']['intid'] 
      date = retrieval['abstracts-retrieval-response']['coredata']['prism:coverDate'] 

      department.append(dep) 
      subj.append(sub) 
      ident.append(iD) 
      dates.append(date) 

      break # Don't do the else 

     except Exception as exception: 
      print ('Problem accessing: {}' .format (url)) 
      print (exception) 
      time.sleep (2) # Seconds 
    else: # Done after for-loop exhausted, but not if 'break' was encountered 
     print ('Gave up accessing: {}' .format (url)) 

注:我沒有測試過這個,但它應該傳達一般想法。 「睡眠」是爲了讓服務器屏住呼吸......

+0

對不起,錯誤消息很長,所以我只發佈了它的一個片段。我會編輯一個編輯來包含整個錯誤,其中包括有效的異常 –

+0

我已經包含了整個錯誤信息,很遺憾,它很長,但它應該包含必要的信息,我相信 –

+0

似乎有一個例外在隨機網址(不知道爲什麼),但一旦異常提出循環進行正常。它就像主機隨機隨機故障 –