Home  >  Article  >  Backend Development  >  How to Change the User Agent in Chrome with Selenium?

How to Change the User Agent in Chrome with Selenium?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 08:51:02976browse

How to Change the User Agent in Chrome with Selenium?

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:

  1. Install the fake_useragent module: This library provides a wide range of user-agents that can be utilized by Selenium WebDriver. Simply install it via pip with the command pip install fake_useragent.
  2. 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>
  3. Create a new Chrome WebDriver instance:

    <code class="python">options = Options()
    ua = UserAgent()
    user_agent = ua.random
    print(user_agent)</code>
  4. Set the custom user agent:

    <code class="python">options.add_argument(f'--user-agent={user_agent}')</code>
  5. 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>
  6. Load the desired webpage:

    <code class="python">driver.get("https://www.bing.com/")</code>
  7. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn