【发布时间】:2017-04-22 12:01:17
【问题描述】:
我正在尝试编写一个脚本,其中一部分必须检查 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 不可用和存在之类的行,那就太好了。
【问题讨论】:
-
所以只是catch the exception?请参阅Errors and Exceptions section。您是否尝试过这个,您是否在定位要捕获的异常时遇到问题?
-
你考虑过捕获和处理异常吗?
标签: python exception python-requests