我正在尝试使用 python-requests
检查过期的域名。
import requests
try:
status = requests.head('http://wowsucherror')
except requests.ConnectionError as exc:
print(exc)
这段代码看起来太通用了。它产生以下输出:
HTTPConnectionPool(host='wowsucherror', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))
我想要的是只捕获这个DNS错误(如Chrome中的ERR_NAME_NOT_RESOLVED
)。如果万不得已,我可以使用字符串匹配,但也许有更好、更结构化和向前兼容的方法来处理这个错误?
理想情况下应该是requests
的一些DNSError
扩展。
更新: Linux上的错误不同。
HTTPConnectionPool(host='wowsucherror', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno -2] Name or service not known',))
向requests
->urllib3
报告了错误https://github.com/shazow/urllib3/issues/1003
更新2: OS X也报告了不同的错误。
requests.exceptions.ConnectionError: HTTPConnectionPool(host='wowsucherror', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))
except (NewConnectionError, socket.error) as exc:
语句,但是socket错误被吞掉了。也许值得发起一个问题,因为这似乎是一个合理的需求,只需要将e.errno传递即可。 - Padraic Cunningham