You can download this code by clicking the button below.
This code is now available for download.
This function uses the Requests library to fetch data from a specified URL and returns the text content of the response. It first defines an internal function get_random_useragent, which randomly selects a user agent string. Then, in the fetch_random_data function, this user agent string is used to send a GET request and the response content is returned.
Technology Stack : Python, Requests
Code Type : Function
Code Difficulty : Intermediate
import random
import requests
def get_random_useragent():
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15",
"Mozilla/5.0 (Linux; Android 10; SM-A505FN) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Mobile Safari/537.36",
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/68.0.3440.70 Mobile/14E5239e Safari/602.1"
]
return random.choice(user_agents)
def fetch_random_data(url):
headers = {'User-Agent': get_random_useragent()}
response = requests.get(url, headers=headers)
return response.text