无法访问URL时的response = requests.get错误

时间:2017-04-22 12:01:17

标签: python exception python-requests

我正在尝试编写一个脚本,其中一部分必须检查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不可用的行,那么存在就会很棒。

1 个答案:

答案 0 :(得分:1)

只是catch the exceptionrequests文档的Errors and Exceptions section表示您应该可以在此处捕获requests.ConnectionError exception

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