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

Barbara Streisand
发布: 2024-10-26 03:05:03
原创
947 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!