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

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

Barbara Streisand
Barbara Streisand原创
2024-10-26 03:05:03939浏览

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

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

在自动化需要特定浏览器配置的任务时,更改 Chrome 中的用户代理至关重要。这可以使用 Selenium 和 Python 来实现。

要启用用户代理开关,请修改选项设置:

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

此参数指定所需的用户代理。在本例中,它模拟 Microsoft Edge Mobile。

但是,提供的代码不会加载网页。要解决此问题:

<code class="python">driver = webdriver.Chrome(chrome_options=opts)
driver.get("https://www.bing.com/")</code>

Python 的 fake_useragent 模块允许随机选择用户代理:

<code class="python">from fake_useragent import UserAgent

ua = UserAgent()
user_agent = ua.random</code>

这提供了一个随每次执行而变化的随机用户代理。

<code class="python">options.add_argument(f'--user-agent={user_agent}')
driver = webdriver.Chrome(chrome_options=options)</code>

现在,多个页面加载的用户代理将会不同。

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

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