Categories
Python Answers

How to change Google Chrome user agent in Selenium in Python?

Spread the love

Sometimes, we want to change Google Chrome user agent in Selenium in Python.

In this article, we’ll look at how to change Google Chrome user agent in Selenium in Python.

How to change Google Chrome user agent in Selenium in Python?

To change Google Chrome user agent in Selenium in Python, we can use the fake_useragent library.

To install it, we run

pip install fake-useragent

Then we write

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent

options = Options()
ua = UserAgent()
userAgent = ua.random

options.add_argument(f'user-agent={userAgent}')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
driver.get("https://www.example.com")
driver.quit()

to create a UserAgent object.

We get a random user agent with ua.random.

And then we call add_argument to add the userAgent into the options object.

Then we create the Chrome webdriver withj the chrome_options set to options to open Chrome with the user agent we set.

Conclusion

To change Google Chrome user agent in Selenium in Python, we can use the fake_useragent library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *