首页  >  文章  >  后端开发  >  如何使用 Selenium 更改 Google Chrome 中的用户代理?

如何使用 Selenium 更改 Google Chrome 中的用户代理?

Susan Sarandon
Susan Sarandon原创
2024-10-26 02:58:27185浏览

How to Change User Agent in Google Chrome with Selenium?

使用 Selenium 更改 Google Chrome 中的用户代理

在 Selenium 中,可以在启动 Chrome 时指定自定义用户代理以模拟不同的浏览设备或环境。为此,您需要在创建 ChromeDriver 实例之前修改 Options 对象。

提供的代码有一些问题:

  • 使用 Options 而不是 import Options: 您的代码导入了 Options 模块,但您实际上并没有创建 Options 对象。您应该将 from selenium.webdriver.chrome.options import Options 替换为 from selenium.webdriver.chrome.options import Options as ChromeOptions。
  • 用户代理设置:您的用户代理字符串提供的是正确的,但它没有正确添加到选项对象中。您需要将 add_argument 与 --user-agent 标志一起使用,后跟所需的用户代理值。
  • 驱动程序路径: 您没有指定 ChromeDriver 实例的路径。您应该使用 ChromeDriver 构造函数的executable_path 参数来指定它。

这是代码的更正版本:

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

以上是如何使用 Selenium 更改 Google Chrome 中的用户代理?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn