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

How to Change the User Agent in Chrome with Selenium and Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 03:05:03939browse

How to Change the User Agent in Chrome with Selenium and Python?

Changing the User Agent in Chrome with Selenium

Changing the user agent in Chrome is essential when automating tasks that require specific browser configurations. This can be achieved using Selenium with Python.

To enable the user agent switch, modify the Options settings:

<code class="python">from selenium import webdriver
from selenium.webdriver.chrome.options import Options

opts = Options()
opts.add_argument("user-agent=Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166")</code>

This argument specifies the desired user agent. In this case, it simulates Microsoft Edge Mobile.

However, the provided code doesn't load the webpage. To fix this:

<code class="python">driver = webdriver.Chrome(chrome_options=opts)
driver.get("https://www.bing.com/")</code>

Python's fake_useragent module allows for random user agent selection:

<code class="python">from fake_useragent import UserAgent

ua = UserAgent()
user_agent = ua.random</code>

This provides a random user agent that changes with each execution.

<code class="python">options.add_argument(f'--user-agent={user_agent}')
driver = webdriver.Chrome(chrome_options=options)</code>

Now, the user agent will be different for multiple page loads.

The above is the detailed content of How to Change the User Agent in Chrome with Selenium and Python?. 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