How to Change the User Agent in Chrome with Selenium?

Mary-Kate Olsen
Release: 2024-10-26 08:51:02
Original
975 people have browsed it

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>
    Copy after login
  3. Create a new Chrome WebDriver instance:

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

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

    <code class="python">driver.get("https://www.bing.com/")</code>
    Copy after login
  7. Quit the WebDriver:

    <code class="python">driver.quit()</code>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!