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:
<code class="python">from selenium import webdriver from selenium.webdriver.chrome.options import Options from fake_useragent import UserAgent</code>
Create a new Chrome WebDriver instance:
<code class="python">options = Options() ua = UserAgent() user_agent = ua.random print(user_agent)</code>
Set the custom user agent:
<code class="python">options.add_argument(f'--user-agent={user_agent}')</code>
Initialize the WebDriver using the modified options:
<code class="python">driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')</code>
Load the desired webpage:
<code class="python">driver.get("https://www.bing.com/")</code>
Quit the WebDriver:
<code class="python">driver.quit()</code>
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.
The above is the detailed content of How to Change the User Agent in Chrome with Selenium?. For more information, please follow other related articles on the PHP Chinese website!