Random Resource Fetcher Function

  • Share this:

Code introduction


This function fetches the content of a specified URL. If an error occurs, it prints the error message.


Technology Stack : Requests

Code Type : Function

Code Difficulty : Intermediate


                
                    
import requests
import random

def fetch_random_resource(url, headers=None):
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.text
    except requests.exceptions.HTTPError as errh:
        print(f"HTTP Error: {errh}")
    except requests.exceptions.ConnectionError as errc:
        print(f"Error Connecting: {errc}")
    except requests.exceptions.Timeout as errt:
        print(f"Timeout Error: {errt}")
    except requests.exceptions.RequestException as err:
        print(f"Error: {err}")                
              
Tags: