You can download this code by clicking the button below.
This code is now available for download.
This function randomly selects a URL from a provided list and fetches its content using the Requests library. If successful, it returns the content; if not, it returns an error message.
Technology Stack : Python, Requests
Code Type : Function
Code Difficulty : Intermediate
import random
import requests
def fetch_random_url_content(urls):
"""
Fetches the content of random URLs from a given list using the requests library.
"""
if not urls:
return "No URLs provided"
random_url = random.choice(urls)
response = requests.get(random_url)
if response.status_code == 200:
return response.text
else:
return f"Failed to retrieve content from {random_url}, status code: {response.status_code}"