How to Spoof Your User Agent in Google Chrome using Selenium?

Mary-Kate Olsen
Release: 2024-10-28 06:21:30
Original
483 people have browsed it

How to Spoof Your User Agent in Google Chrome using Selenium?

How to Modify the User Agent in Selenium for Google Chrome

Changing the user agent in Chrome using Selenium in Python is a common requirement for various testing scenarios. To accomplish this, you can employ the following approach:

Start by importing the necessary libraries, including Selenium and the Options module for modifying Chrome options.

<code class="python">from selenium import webdriver
from selenium.webdriver.chrome.options import Options</code>
Copy after login

Next, create an instance of Options and add the desired user agent using the add_argument() method. In this example, we'll set the user agent to simulate Microsoft Edge Mobile:

<code class="python">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

Now, create a new Chrome driver instance with the modified options:

<code class="python">driver = webdriver.Chrome(chrome_options=opts)</code>
Copy after login

Finally, navigate to the desired webpage using the get() method:

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

By following these steps, you can set a custom user agent for Chrome when opening it via Selenium, allowing you to test websites from the perspective of a different browser or device.

The above is the detailed content of How to Spoof Your User Agent in Google Chrome using 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