How to Change User Agent in Chrome Using Selenium?
One of the common challenges faced by web developers while automating tasks using Selenium and Chrome is changing the default user agent of the browser. This can be necessary for compatibility with certain websites or applications.
To modify the user agent in Chrome via Selenium, you can use the following steps:
Import the necessary Python libraries:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
Create a new Chrome WebDriver instance:
options = Options()
ua = UserAgent()
user_agent = ua.random
print(user_agent)
Set the custom user agent:
options.add_argument(f'--user-agent={user_agent}')
Initialize the WebDriver using the modified options:
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
Load the desired webpage:
driver.get("https://www.bing.com/")
Quit the WebDriver:
driver.quit()
This approach leverages the fake_useragent module to automatically select and set a random user agent, providing flexibility and ensuring compatibility with numerous websites and applications.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3