Python: How to check if URL is reachable

In this tutorial, I'll show you an efficient way to check if the URL is reachable and, for this purpose, we'll use the requests library.

Install requests via pip:

pip install requests

Now let's write the checker code.

import requests

def url_checker(url):
		#Get Url
		get = requests.get(url)
		# if the request succeeds 
		if get.status_code == 200:
			return(f"{url}: is reachable")
			return(f"{url}: is Not reachable, status_code: {get.status_code}")

	except requests.exceptions.RequestException as e:
        # print URL with Errs
		raise SystemExit(f"{url}: is Not reachable \nErr: {e}")

What we've did?

  1. requesting for the URL using the get method
  2. checking if the request status is 200

We've use Try and Except to handle the exceptions of requests library.

requests.exceptions.RequestException: All exceptions that Requests explicitly raises inherit from.

Now, it's time to test our program.


Output: is reachable

Try a URL that's not working.


Output: is Not reachable
Err: HTTPConnectionPool(host='', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ffad7fc6850>: Failed to establish a new connection: [Errno -2] Name or service not known'))