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.
You can try the following steps in order to resolve the 403 error in the browser try refreshing the page, rechecking the URL, clearing the browser cookies, check your user credentials.
Requests - Requests' is a simple, easy-to-use HTTP library written in Python. 1) Python Requests encodes the parameters automatically so you just pass them as simple arguments, unlike in the case of urllib, where you need to use the method urllib. encode() to encode the parameters before passing them.
Urllib package is the URL handling module for python. It is used to fetch URLs (Uniform Resource Locators). It uses the urlopen function and is able to fetch URLs using a variety of different protocols. Urllib is a package that collects several modules for working with URLs, such as: urllib.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With