gpt4 book ai didi

dns - 使用 Python 请求精确捕获 DNS 错误

转载 作者:行者123 更新时间:2023-12-05 00:49:28 24 4
gpt4 key购买 nike

我正在尝试使用 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

UPDATE2: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',))

最佳答案

通过这个 hack 完成此操作,但请监视 https://github.com/psf/requests/issues/3630以正确的方式出现。

# for Python 2 compatibility
from __future__ import print_function
import requests

def sitecheck(url):
status = None
message = ''
try:
resp = requests.head('http://' + url)
status = str(resp.status_code)
if ("[Errno 11001] getaddrinfo failed" in str(exc) or # Windows
"[Errno -2] Name or service not known" in str(exc) or # Linux
"[Errno 8] nodename nor servname " in str(exc)): # OS X
message = 'DNSLookupError'
else:
raise

return url, status, message

print(sitecheck('wowsucherror'))
print(sitecheck('google.com'))

关于dns - 使用 Python 请求精确捕获 DNS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40145631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com