"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 and Python?

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

Published on 2024-11-16
Browse:966

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:

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")

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:

driver = webdriver.Chrome(chrome_options=opts)
driver.get("https://www.bing.com/")

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

from fake_useragent import UserAgent

ua = UserAgent()
user_agent = ua.random

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

options.add_argument(f'--user-agent={user_agent}')
driver = webdriver.Chrome(chrome_options=options)

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

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