gpt4 book ai didi

python-3.x - python3中的urllib异常处理

转载 作者:行者123 更新时间:2023-12-03 07:46:33 25 4
gpt4 key购买 nike

我正在 try catch 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:

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

最佳答案

试试这个,它对我有用:

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

希望对你有用。

关于python-3.x - python3中的urllib异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53755173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com