You can download this code by clicking the button below.
This code is now available for download.
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)