[英]response = requests.get error when URL is not reachable
我正在嘗試編寫一個腳本,它的一部分必須檢查 URL 是否可用。 問題是,當我收到 200,404 等回復時,程序運行良好,我可以處理回復,但是當無法訪問 URL 時,程序會出現以下錯誤。 這是代碼的一部分:
response = requests.get(url)
print (response)
錯誤:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\requests\packages\urllib3\connection.py", line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "C:\Python\lib\site-packages\requests\packages\urllib3\util\connection.py", line 60, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "C:\Python\lib\socket.py", line 743, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:\Python\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 345, in _make_request
self._validate_conn(conn)
File "C:\Python\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 844, in _validate_conn
conn.connect()
File "C:\Python\lib\site-packages\requests\packages\urllib3\connection.py", line 284, in connect
conn = self._new_conn()
File "C:\Python\lib\site-packages\requests\packages\urllib3\connection.py", line 150, in _new_conn
self, "Failed to establish a new connection: %s" % e)
requests.packages.urllib3.exceptions.NewConnectionError: <requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03EC9970>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
有解決方法嗎? 如果我可以將腳本設置為打印諸如 URL not available and exists 之類的行,那就太好了。
只需捕獲異常。 requests
文檔的錯誤和異常部分表明您應該能夠在此處捕獲requests.ConnectionError
異常:
try:
response = requests.get(url)
except requests.ConnectionError:
print("Can't connect to the site, sorry")
else:
print(response)
使用不存在的主機名的快速演示:
>>> import requests
>>> try:
... response = requests.get("http://no_such_site_exists.imsure")
... except requests.ConnectionError:
... print("Can't connect to the site, sorry")
... else:
... print(response)
...
Can't connect to the site, sorry
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.