How to Change User Agent in Google Chrome with Selenium?

Susan Sarandon
Release: 2024-10-26 02:58:27
Original
184 people have browsed it

How to Change User Agent in Google Chrome with Selenium?

Changing User Agent in Google Chrome with Selenium

In Selenium, it is possible to specify a custom user agent when launching Chrome to simulate different browsing devices or environments. To achieve this, you need to modify the Options object before creating the ChromeDriver instance.

The provided code has a few issues:

  • Use Options Instead of import Options: Your code imports the Options module, but you're not actually creating an Options object. You should replace from selenium.webdriver.chrome.options import Options with from selenium.webdriver.chrome.options import Options as ChromeOptions.
  • User Agent Setting: The user agent string you've provided is correct, but it's not being properly added to the Options object. You need to use add_argument with the --user-agent flag, followed by the desired user agent value.
  • Driver Path: You're not specifying the path to your ChromeDriver instance. You should specify it using the executable_path parameter of the ChromeDriver constructor.

Here's a corrected version of your code:

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

opts = ChromeOptions()
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")
driver = webdriver.Chrome(chrome_options=opts, executable_path="PATH_TO_CHROME_DRIVER")
driver.get("https://www.bing.com/")</code>
Copy after login

The above is the detailed content of How to Change User Agent in Google Chrome with 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!