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>
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>
Now, create a new Chrome driver instance with the modified options:
<code class="python">driver = webdriver.Chrome(chrome_options=opts)</code>
Finally, navigate to the desired webpage using the get() method:
<code class="python">driver.get("https://www.bing.com/")</code>
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!