Random Image Fetcher from URL

  • Share this:

Code introduction


The function fetches a random image from a specified URL and saves it to the local file system.


Technology Stack : requests, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import requests
from random import choice

def fetch_random_image(url):
    """
    Fetches a random image from a given URL and saves it to a file.
    """
    response = requests.get(url)
    response.raise_for_status()
    image_name = url.split('/')[-1]
    with open(image_name, 'wb') as file:
        file.write(response.content)