Python requests check status code

Python -- Posted on July 28, 2023

You can use the Python requests library to check if the status code of a URL is 200 without actually downloading the file content. When you make a request using requests.get(), the response object will contain the status code, headers, and other metadata.

In this example, we set stream=True when making the request. This prevents requests from automatically downloading the file content. Instead, it allows us to inspect the status code and other metadata from the response.

              
                import requests

def check_url_status(url):
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            print("URL is accessible (status code 200).")
        else:
            print(f"URL is not accessible. Status code: {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")

# Example usage:
url_to_check = "https://example.com/somefile.txt"
check_url_status(url_to_check)
                  
   
            

Related Posts