-3
我想寫一個腳本,它的一部分必須檢查URL是否可用。問題是,當我得到回覆200,404等,該程序工作正常,我可以處理的答覆,但是當URL無法訪問,程序進入下面的錯誤。 這是部分代碼:response = requests.get錯誤,當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不可用的行,並且存在將會很好。
所以剛纔[捕獲異常(HTTPS:/ /docs.python.org/3/tutorial/errors.html#handling-exceptions)?請參閱[*錯誤和例外*部分](http://docs.python-requests.org/en/master/user/quickstart/#errors-and-exceptions)。你有沒有嘗試過這個,你有沒有遇到問題要找到什麼異常? –
你有沒有考慮捕捉和處理異常? – mhawke