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

Barbara Streisand
Release: 2024-10-26 03:05:03
Original
947 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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!