Search code examples
pythonpython-3.xurllib

Python 3 - urllib.request - HTTPError


    import urllib.request
request = urllib.request.Request('http://1.0.0.8/')
try:
    response = urllib.request.urlopen(request)
    print("Server Online")
    #do stuff here
except urllib.error.HTTPError as e: # 404, 500, etc..
    print("Server Offline")
    #do stuff here

I'm trying to write a simple program that will check a list of LAN webserver is up. Currently just using one IP for now.

When I run it with an IP of a web server I get back Server Online.

When I run it with a IP that doesn't have web server I get

"urllib.error.URLError: <urlopen error [WinError 10061] No connection could be made because the target machine actively refused it>" 

but would rather a simple "Server Offline" output. Not sure how to get the reply to output Server Offline.


Solution

  • In your code above you’re just looking for HTTPError exceptions. Just add another except clause to the end that would reference the exception that you are looking for, in this case the URLError:

    import urllib.request
    request = urllib.request.Request('http://1.0.0.8/')
    try:
        response = urllib.request.urlopen(request)
        print("Server Online")
        #do stuff here
    except urllib.error.HTTPError as e:
         print("Server Offline")
         #do stuff here
    except urllib.error.URLError as e:
         print("Server Offline")
         #do stuff here