除了处理请求

2024-04-24 10:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我故意检查一个错误的url:https://google55.com,以便查看如何处理错误。你知道吗

我确实有一些except,但是他们似乎什么也没做。你知道吗

h = {
    'Server': server, 
    'User-Agent': server + ' (Node 01)', 
}
try:
    resp = requests.head("https://google55.com", headers=h) 
except requests.exceptions.Timeout:
    print ('Timeout...')
except requests.exceptions.TooManyRedirects:
    print ('Bad URL...')
except requests.exceptions.RequestException as e:
    print (e)

因为我得到以下错误:

HTTPSConnectionPool(host='google55.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0xffff99595978>: Failed to establish a new connection: [Errno -2] Name or service not known',))
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/urllib3/connection.py", line 160, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "/usr/local/lib/python3.6/dist-packages/urllib3/util/connection.py", line 57, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "/usr/lib/python3.6/socket.py", line 745, 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 "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 603, in urlopen
chunked=chunked)
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 344, in _make_request
self._validate_conn(conn)
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 843, in _validate_conn
conn.connect()
File "/usr/local/lib/python3.6/dist-packages/urllib3/connection.py", line 316, in connect
conn = self._new_conn()
File "/usr/local/lib/python3.6/dist-packages/urllib3/connection.py", line 169, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0xffff99595978>: Failed to establish a new connection: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py", line 641, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/local/lib/python3.6/dist-packages/urllib3/util/retry.py", line 399, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='google55.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0xffff99595978>: Failed to establish a new connection: [Errno -2] Name or service not known',))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "uptime_test1.py", line 12, in <module>
resp = requests.head("https://google55.com", headers=h)
File "/usr/local/lib/python3.6/dist-packages/requests/api.py", line 101, in head
return request('head', url, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.6/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='google55.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0xffff99595978>: Failed to establish a new connection: [Errno -2] Name or service not known',))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "uptime_test1.py", line 28, in <module>
sys.exit(1)
NameError: name 'sys' is not defined
root@gateway:/var/www/default/python/uptime# 
root@gateway:/var/www/default/python/uptime# 
root@gateway:/var/www/default/python/uptime# 
root@gateway:/var/www/default/python/uptime# 
root@gateway:/var/www/default/python/uptime# 
root@gateway:/var/www/default/python/uptime# 
root@gateway:/var/www/default/python/uptime# python3 uptime_test1.py 
HTTPSConnectionPool(host='google55.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0xffff89210978>: Failed to establish a new connection: [Errno -2] Name or service not known',))
Status
Traceback (most recent call last):
File "uptime_test1.py", line 31, in <module>
print (resp.status_code)
NameError: name 'resp' is not defined

需要以某种方式捕获此错误,以便脚本知道它是一个错误的URL。你知道吗


Tags: inpyurlnewlibpackagesusrlocal
2条回答

如果处理的异常不正确,可以在堆栈跟踪中检查实际引发的异常,然后捕获它们。跟踪中的一些异常:

urllib3.exceptions.NewConnectionError
urllib3.exceptions.MaxRetryError
requests.exceptions.ConnectionError
NameError
# ... none of which you're handling

尽管requests.exceptions.TooManyRedirectsurllib3.exceptions.MaxRetryErrormy似乎有相同的原因,但异常本身并不相同。你知道吗

这是代码的相关部分:

Traceback (most recent call last):
File "uptime_test1.py", line 31, in <module>
print (resp.status_code)
NameError: name 'resp' is not defined

这是一个NameError异常。您的resp变量未在File "uptime_test1.py", line 31, in <module>中定义。可能,您希望在if分支中设置此变量,而您的代码不会运行到此if。你知道吗

但如果要处理此异常,可以尝试:

try:
    print (resp.status_code)
except NameError:
    print("Undefined variable")

注意:如果检查回溯,您可以看到代码中没有处理的更多requests.exceptions.Xurllib3.exceptions.X异常。你知道吗

相关问题 更多 >