Last modified: Nov 04, 2023 By Alexander Williams

Python: How to Check if a URL Returns a 404 Not Found Error

Example 1: Using the requests Library

        
import requests

# Define the URL to check
url = "https://example.com/nonexistent-page"

# Send a GET request to the URL
response = requests.get(url)

# Check if the response status code is 404
if response.status_code == 404:
    print("The URL returns a 404 Not Found error.")
else:
    print("The URL is accessible.")
        
    

Output:

        
The URL returns a 404 Not Found error.
        
    

Example 2: Using the urllib Library

        
import urllib.request

# Define the URL to check
url = "https://example.com/nonexistent-page"

try:
    # Send a GET request to the URL
    response = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
    if e.code == 404:
        print("The URL returns a 404 Not Found error.")
    else:
        print("The URL is accessible.")
        
    

Output:

        
The URL returns a 404 Not Found error.