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

在本文中,将演示如何为浏览器设置用户代理,以及如何在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浏览器在其用户代理数据中添加了大量信息。

猜你喜欢

转载自blog.csdn.net/captain5339/article/details/131115158
今日推荐