【问题标题】:response = requests.get error when URL is not reachable无法访问 URL 时的 response = requests.get 错误
【发布时间】: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 不可用和存在之类的行,那就太好了。

【问题讨论】:

标签: python exception python-requests


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 2022-01-13
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多