You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

2024年Selenium替代selenium-wire捕获请求头及响应的方案咨询

Selenium 替代 Selenium-Wire 的方案及框架迁移建议

一、在Selenium内实现需求的替代方案

1. 利用Selenium 4+的DevTools API捕获请求/Token

Selenium 4及以上版本原生支持Chrome DevTools Protocol(CDP),可以通过监听网络事件来捕获OAuth流程中的token,无需依赖第三方库:

from selenium import webdriver
from selenium.webdriver.common.devtools.v120 import network
import json

driver = webdriver.Chrome()
devtools = driver.devtools

# 启用Network监控
devtools.send(network.enable())

# 存储捕获到的token
captured_tokens = []

def intercept_oauth_token(event):
    response = event.get("response")
    request_url = response.get("url")
    # 匹配你的OAuth token发放端点(根据实际场景调整)
    if "/oauth2/token" in request_url:
        # 获取响应体内容
        resp_body = devtools.send(network.getResponseBody(requestId=event["requestId"]))
        token_payload = json.loads(resp_body["body"])
        captured_tokens.append(token_payload.get("access_token"))

# 绑定响应监听事件
devtools.on(network.responseReceived, intercept_oauth_token)

# 执行OAuth认证流程(模拟用户操作完成登录)
driver.get("https://your-auth-domain.com/login")
# 此处添加用户名、密码输入、提交等操作代码...

# 认证完成后提取token
if captured_tokens:
    target_token = captured_tokens[-1]
    # 后续可使用该token调用session、revoke等后端API
    print(f"获取到access_token: {target_token}")

这种方式可以精准捕获网络请求中的token,覆盖大多数OAuth授权码/密码模式的场景。

2. 从浏览器存储提取Token(如果适用)

如果你的被测系统会将access_token存入localStorage或sessionStorage,可以直接通过execute_script提取,实现更简单:

access_token = driver.execute_script("return localStorage.getItem('access_token');")
# 或针对sessionStorage
# access_token = driver.execute_script("return sessionStorage.getItem('access_token');")

注意:此方法仅适用于前端主动存储token的场景,若token仅存在于请求头或响应体中则不适用。

二、是否需要更换框架?

如果你的需求仅局限于捕获OAuth Token并调用后端API,上述Selenium内置方案完全可以满足,无需更换框架。

但如果需要更复杂的网络操作(如拦截并重写请求/响应、Mock接口、批量监控请求),更换框架会更省心:

  • Cypress:原生cy.intercept()功能对网络操作的支持非常成熟,语法简洁,适合端到端测试场景,对OAuth流程的适配也很友好。
  • Playwright:内置强大的网络拦截与请求监听API,跨浏览器兼容性好,支持直接发起API请求并与浏览器操作无缝联动,代码风格更现代。

内容的提问来源于stack exchange,提问作者James Windshield

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 16:27:26