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 a random user agent and send it as a request header to httpbin.org to get the current IP address and user agent information.
Technology Stack : requests
Code Type : The type of code
Code Difficulty : Intermediate
import requests
from requests.exceptions import RequestException
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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 UBrowser/9.0 Safari/537.36"
]
return requests.utils.get_random_useragent()
def fetch_random_useragent():
try:
user_agent = get_random_useragent()
response = requests.get("https://httpbin.org/ip", headers={"User-Agent": user_agent})
response.raise_for_status()
return response.json()
except RequestException as e:
return {"error": str(e)}