[Python] selenium如何获取请求头参数?seleniumwire

Seleniumwire是Selenium Python库的一个扩展,允许开发者访问和操作浏览器发出的底层HTTP请求。它支持Chrome、Firefox和Remote Webdriver。通过这个库,可以方便地获取登录网站所需的cookies和token等加密参数,为后续的数据抓取提供便利。安装Seleniumwire只需通过pip,并且使用方式与Selenium基本一致,同时提供了检查和修改请求及响应的API。

Seleniumwire 扩展了 Selenium 的 Python 绑定,让您可以访问浏览器发出的底层请求。 您编写代码的方式与使用 Selenium 的方式相同,但您可以获得额外的 API 来检查请求和响应并动态更改它们。

1.环境要求

  • Python 3.6+
  • Selenium 3.4.0+
  • Chrome, Firefox and Remote Webdriver supported

2.安装

pip install selenium-wire

3.示例

from seleniumwire import webdriver

driver = webdriver.Chrome()

driver.get('https://www.google.com')

for request in driver.requests:
    if request.response:
        print(
            request.url,
            request.response.status_code,
            request.response.headers['Content-Type']
        )

4.总结
该模块常用于需要登录网站的cookies和token等加密参数的获取,为后续采集程序提供通行凭证。

转载:http://pyspiderking.cn/index.php/2021/07/31/seleniumwire/

### 在 Python 中使用 Selenium 设置请求头中的 Authorization 值 在 PythonSelenium 中,原生的 WebDriver 并不直接支持修改 HTTP 请求头[^1]。然而,可以通过第三方库 `selenium-wire` 实现这一功能,该库扩展了 Selenium 的能力,允许拦截和修改请求头。 以下是一个完整的解决方案,展示如何使用 `selenium-wire` 来设置 `Authorization` 值: ```python from seleniumwire import webdriver # pip install selenium-wire from selenium.webdriver.common.by import By # 定义一个拦截器函数,用于修改所有请求的头部信息 def interceptor(request): request.headers['Authorization'] = 'Bearer your_token_here' # 设置 Authorization 值 # 初始化 Chrome 浏览器实例,并设置请求拦截器 options = { 'request_interceptor': interceptor # 将拦截器应用到每个请求 } browser = webdriver.Chrome(seleniumwire_options=options) # 打开目标网页 browser.get('https://example.com') # 示例:检查页面加载是否成功(可选) element = browser.find_element(By.TAG_NAME, 'h1') print(element.text) ``` 上述代码中,通过定义 `interceptor` 函数并将其设置为 `seleniumwire_options` 的一部分,可以确保每次请求都包含指定的 `Authorization` 值[^3]。 --- #### 使用 Selenium 自带功能尝试设置 Headers(不推荐) 如果无法使用 `selenium-wire`,也可以尝试通过 JavaScript 注入的方式来模拟设置请求头。但需要注意,这种方法仅适用于特定场景,并不能真正修改浏览器发起的所有请求头[^2]。以下是一个示例: ```python from selenium import webdriver # 初始化 Chrome 浏览器实例 browser = webdriver.Chrome() # 使用 JavaScript 模拟设置 Authorization 头部信息 script = """ var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com', true); xhr.setRequestHeader('Authorization', 'Bearer your_token_here'); xhr.send(); """ browser.execute_script(script) ``` 此方法仅适用于通过 JavaScript 发起的请求,而无法影响浏览器本身的网络请求[^2]。 --- #### 验证 Headers 是否正确设置 为了验证 `Authorization` 值是否已正确设置,可以利用 `selenium-wire` 提供的请求记录功能来检查实际发出的请求头: ```python # 遍历所有请求,查找目标 URL 的请求头 for request in browser.requests: if request.response and 'example.com' in request.url: print(request.headers) # 输出请求头以验证 Authorization 值 ``` 通过上述代码,可以确认 `Authorization` 是否被正确添加到请求头中[^3]。 ---
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值