"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Change the User Agent in Chrome with Selenium?

How to Change the User Agent in Chrome with Selenium?

Published on 2024-11-22
Browse:826

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:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from fake_useragent import UserAgent
  3. Create a new Chrome WebDriver instance:

    options = Options()
    ua = UserAgent()
    user_agent = ua.random
    print(user_agent)
  4. Set the custom user agent:

    options.add_argument(f'--user-agent={user_agent}')
  5. Initialize the WebDriver using the modified options:

    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
  6. Load the desired webpage:

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

Latest tutorial More>

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