Skip to content Skip to sidebar Skip to footer

Precisely Catch Dns Error With 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 a

Solution 1:

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

# for Python 2 compatibilityfrom __future__ import print_function
import requests

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

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

Solution 2:

You could use lower-level network interface, socket.getaddrinfohttps://docs.python.org/3/library/socket.html#socket.getaddrinfo

import socket


defdns_lookup(host):
    try:
        socket.getaddrinfo(host, 80)
    except socket.gaierror:
        returnFalsereturnTrueprint(dns_lookup('wowsucherror'))
print(dns_lookup('google.com'))

Solution 3:

I have a function based on the earlier answer above which seems to no longer work. This function checks "liveness" of a url based on resolution and also the requests .ok function rather than just specific to resolution errors but can be adapted easily to suit.

defcheck_live(url):
    try:
        r = requests.get(url)
        live = r.ok
    except requests.ConnectionError as e:
        if'MaxRetryError'notinstr(e.args) or'NewConnectionError'notinstr(e.args):
            raiseif"[Errno 8]"instr(e) or"[Errno 11001]"instr(e) or ["Errno -2"] instr(e):
            print('DNSLookupError')
            live = Falseelse:
            raiseexcept:
        raisereturn live

Post a Comment for "Precisely Catch Dns Error With Python Requests"