Python 官方文档:入门教程 => 点击学习
在本文中,将演示如何为浏览器设置用户代理,以及如何在python selenium WEBDriver中读取用户代理。测试中的许多方案都需要操作用户代理。 什么是用户代理? User-Agent 请求
在本文中,将演示如何为浏览器设置用户代理,以及如何在python selenium WEBDriver中读取用户代理。测试中的许多方案都需要操作用户代理。
User-Agent 请求标头包含一个特征字符串,该字符串允许网络协议对等方标识请求软件用户代理的应用程序类型、操作系统、软件供应商或软件版本。它显示在 Http 请求标头中,不适用于响应标头。所有浏览器都支持它。
简而言之,用户代理是客户端(用户)的身份。
用户代理的通过格式:
User-Agent: Mozilla/ () ()
Example:
Mozilla/5.0 (windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:63.0) Gecko/20100101 Firefox/63.0
Selenium 没有实现任何直接方法来读取请求或响应标头。
注意:要运行以下示例,您需要在 PATH 环境变量中设置浏览器驱动程序路径详细信息,或者在创建浏览器实例时必须将浏览器驱动程序路径传递给executable_path变量。
Selenium没有任何直接的方法可以从WebDriver实例查询用户代理。我们需要使用执行javascript内置方法来执行此操作,并传递返回user-agent的脚本。
浏览器启动后,我们可以通过执行以下代码行来获取用户代理
# Store it in a variable and print the valueagent = driver.execute_script("return navigator.userAgent")print(agent)# directly print the valueprint(driver.execute_script("return navigator.userAgent"))
要更改 Firefox 浏览器的用户代理,请在 Firefox 配置文件中设置变量“general.useragent.override”,并在创建 Firefox WebDriver 实例时使用此配置文件。
from selenium import webdriverprofile = webdriver.FirefoxProfile()profile.set_preference("general.useragent.override", "[user-agent string]")# Below is tested line# profile.set_preference("general.useragent.override", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:63.0) Gecko/20100101 Firefox/63.0")driver = webdriver.Firefox(profile)
在 Chrome 中,必须使用Options 对象来设置用户代理值。
from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsopts = Options()opts.add_argument("user-agent=[user-agent string]")# Below is tested line# opts.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/71.0.3578.98 Safari/537.36")driver = webdriver.Chrome(chrome_options=opts)
Alternative way to pass driver path along with other details:
可选地,在传递驱动路径时,同时传递其它数据,如下
driver = webdriver.Firefox(profile, executable_path="path to geckodriver")
driver = webdriver.Chrome(chrome_options=opts, executable_path="path to chromedriver")
注:没有编写用户代理字符串的标准方式; 不同的Web浏览器使用不同的格式(有些格式大不相同),并且许多Web浏览器在其用户代理数据中添加了大量信息。
来源地址:https://blog.csdn.net/captain5339/article/details/131115158
--结束END--
本文标题: Python Selenium WebDriver 如何设置请求头用户代理(User-Agent)参数
本文链接: https://www.lsjlt.com/news/394752.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0