python3中的urllib异常处理

时间:2018-12-13 04:49:36

标签: python-3.x error-handling urllib

我正在尝试捕获urllib错误:

Traceback (most recent call last):
  File "/usr/lib64/python3.7/urllib/request.py", line 1317, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/usr/lib64/python3.7/http/client.py", line 1229, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib64/python3.7/http/client.py", line 1275, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib64/python3.7/http/client.py", line 1224, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib64/python3.7/http/client.py", line 1016, in _send_output
    self.send(msg)
  File "/usr/lib64/python3.7/http/client.py", line 956, in send
    self.connect()
  File "/usr/lib64/python3.7/http/client.py", line 928, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/usr/lib64/python3.7/socket.py", line 707, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/lib64/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 190, in on_search_click
    res = ast.literal_eval(urlopen(url).read().decode())
  File "/usr/lib64/python3.7/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib64/python3.7/urllib/request.py", line 525, in open
    response = self._open(req, data)
  File "/usr/lib64/python3.7/urllib/request.py", line 543, in _open
    '_open', req)
  File "/usr/lib64/python3.7/urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "/usr/lib64/python3.7/urllib/request.py", line 1345, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "/usr/lib64/python3.7/urllib/request.py", line 1319, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>

我尝试过:

   except URLError:
     ...

还有

except urllib.error.URLError:

但是已知其中的一个会给出错误,只需打印上面的回溯即可。 我应该如何捕捉错误?

1 个答案:

答案 0 :(得分:0)

尝试一下,它对我有用:

import urllib.error

...

try:
    post = urllib.request.urlopen(request)
    print(post.__dict__)
except urllib.error.HTTPError as e:
    print(e.__dict__)
except urllib.error.URLError as e:
    print(e.__dict__)

我希望它对您有用。