In this article we will see how to check the status of a URL with Python using the requests module.
We can perform a HEAD request and check if the returned HTTP status code is not equal to or greater than 400.
import requests
def check_url(url=None):
if url is None:
return False
ok = True
try:
res = requests.head(url)
ok = True if res.status_code >= 200 and res.status_code < 400 else False
except requests.exceptions.RequestException:
ok = False
return ok
In case of HTTP errors or connection errors, our function will return the boolean value False
.