Python 3 - urllib.request - HTTPError
Asked Answered
O

2

6
    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.

Ockham answered 25/6, 2018 at 13:53 Comment(0)
M
6

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
Morrissey answered 25/6, 2018 at 14:4 Comment(1)
The key here is to put HTTPError before URLError such that the "sub-exception" is raised first.Burin
C
1

well, we could combine the errors as well.

except (urllib.error.URLError, urllib.error.HTTPError):
     print("Poor server is offline.")
Cadi answered 16/6, 2021 at 9:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.