Python Selenium WebDriver 如何设置请求头用户代理(User-Agent)参数

本文介绍了如何在浏览器中设置用户代理,特别是在Python的SeleniumWebDriver中。通过执行JavaScript获取用户代理值,而在Firefox中,可以使用FirefoxProfile设置,Chrome则通过Options对象添加参数。文章还提供了示例代码来展示具体操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在本文中,将演示如何为浏览器设置用户代理,以及如何在Python Selenium WebDriver中读取用户代理。测试中的许多方案都需要操作用户代理。

什么是用户代理?

User-Agent 请求标头包含一个特征字符串,该字符串允许网络协议对等方标识请求软件用户代理的应用程序类型、操作系统、软件供应商或软件版本。它显示在 HTTP 请求标头中,不适用于响应标头。所有浏览器都支持它。

简而言之,用户代理是客户端(用户)的身份。

用户代理的通过格式:

User-Agent: Mozilla/<version> (<system-information>) <platform> (<platform-details>) <extensions>

Example:

Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
Mozilla/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 value
agent = driver.execute_script("return navigator.userAgent")
print(agent)
# directly print the value
print(driver.execute_script("return navigator.userAgent"))

Firefox 中的用户代理设置:

要更改 Firefox 浏览器的用户代理,请在 Firefox 配置文件中设置变量“general.useragent.override”,并在创建 Firefox WebDriver 实例时使用此配置文件。

from selenium import webdriver

profile = 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 中的用户代理设置:

在 Chrome 中,必须使用Options 对象来设置用户代理值。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

opts = 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浏览器在其用户代理数据中添加了大量信息。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值