首页 > 解决方案 > python3中的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:

但是知道他们给出了错误,只是打印了上面的回溯。我应该如何捕捉错误?

标签: python-3.xerror-handlingurllib

解决方案


试试这个,它对我有用:

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__)

我希望这个对你有用。


推荐阅读