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

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

本文介绍了使用Python请求精确捕获DNS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python-requests 检查过期的域名.

I am trying to make a check for expired domain name with python-requests.

import requests

try:
    status = requests.head('http://wowsucherror')
except requests.ConnectionError as exc:
    print(exc)

这段代码看起来太通用了.它产生以下输出:

This code looks too generic. It produces the following output:

我想做的只是仅捕获此DNS错误(例如Chrome中的 ERR_NAME_NOT_RESOLVED ).作为最后的选择,我只能进行字符串匹配,但是也许有更好,更结构化和前向兼容的方式来处理此错误?

What I'd like to do is to catch this DNS error only (like ERR_NAME_NOT_RESOLVED in Chrome). As a last resort I can just do string matching, but maybe there is a better, more structured and forward compatible way of dealing with this error?

理想情况下,它应该是 requests 的某些 DNSError 扩展名.

Ideally it should be some DNSError extension to requests.

更新:Linux上的错误有所不同.

UPDATE: The error on Linux is different.

已将错误报告给 requests -> urllib3 https://github.com/shazow/urllib3/issues/1003

Reported bug to requests -> urllib3 https://github.com/shazow/urllib3/issues/1003

UPDATE2 :OS X还报告了不同的错误.

UPDATE2: OS X also reports different error.

推荐答案

使用此技巧完成了此操作,但请监视 https://github.com/kennethreitz/requests/issues/3630 ,以找到合适的显示方式.

Done this with this hack, but please monitor https://github.com/kennethreitz/requests/issues/3630 for a proper way to appear.

import requests

def sitecheck(url):
    status = None
    message = ''
    try:
        resp = requests.head('http://' + url)
        status = str(resp.status_code)
    except requests.ConnectionError as exc:
        # filtering DNS lookup error from other connection errors
        # (until https://github.com/shazow/urllib3/issues/1003 is resolved)
        if type(exc.message) != requests.packages.urllib3.exceptions.MaxRetryError:
            raise
        reason = exc.message.reason
        if type(reason) != requests.packages.urllib3.exceptions.NewConnectionError:
            raise
        if type(reason.message) != str:
            raise
        if ("[Errno 11001] getaddrinfo failed" in reason.message or     # Windows
            "[Errno -2] Name or service not known" in reason.message or # Linux
            "[Errno 8] nodename nor servname " in reason.message):      # OS X
            message = 'DNSLookupError'
        else:
            raise

    return url, status, message

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

这篇关于使用Python请求精确捕获DNS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 15:09