Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 607
Sabbathlives Avatar asked Jun 25 '18 13:06

Sabbathlives


People also ask

How do I fix Error 403 Forbidden in Python?

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.

Which is better Urllib or requests?

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.

What is Urllib request Urlopen in Python?

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.


1 Answers

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
like image 129
Yaztown Avatar answered Oct 05 '22 23:10

Yaztown