from fake_useragent import UserAgent ua = UserAgent() print(ua.chrome) # prints a random Chrome user agent string print(ua.safari) # prints a random Safari user agent string print(ua.edge) # prints a random Edge user agent string headers = {'User-Agent': ua.chrome} response = requests.get(url, headers=headers)
from fake_useragent import UserAgent from selenium import webdriver ua = UserAgent() options = webdriver.ChromeOptions() options.add_argument(f'user-agent={ua.chrome}') driver = webdriver.Chrome(options=options) driver.get(url)In this example, we use a similar approach to the previous one, but this time we are using the `selenium` library to automate a web browser (Chrome) instead of making HTTP requests. We create a ChromeOptions object, add a `user-agent` argument to it using a randomly generated user agent string, and use this options object to create a Chrome webdriver instance. We can then use this instance to navigate to a website, like with `driver.get(url)`. Overall, fake_useragent is a useful library for generating user agent strings in Python, and can be used in a variety of contexts (e.g. web scraping, automation, testing).