无法通过请求

时间:2016-12-06 08:01:11

标签: python exception-handling python-requests

我这样做:

import requests
r = requests.get("http://non-existent-domain.test")

获得

ConnectionError: HTTPConnectionPool(host='non-existent-domain.test', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x10b0170f0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

但是,如果我试着像这样抓住它:

try:
    r = requests.get("http://non-existent-domain.test")
except ConnectionError:
    print("ConnectionError")

没有任何变化,我仍然无法处理ConnectionError。如何抓住它?

1 个答案:

答案 0 :(得分:5)

这是一个不同的ConnectionError。您正在捕获内置的,但requests有自己的。所以这应该是

try:
    r = requests.get("http://non-existent-domain.test")
except requests.ConnectionError:
    print("ConnectionError")

# Output: ConnectionError