Selenium自动化测试时,如何用mitmproxy精准抓包和修改响应?保姆级避坑指南

张开发
2026/4/19 20:22:08 15 分钟阅读

分享文章

Selenium自动化测试时,如何用mitmproxy精准抓包和修改响应?保姆级避坑指南
Selenium自动化测试中mitmproxy的高级流量操控实战当你在Selenium自动化测试中遇到需要模拟特定网络条件、修改API响应或绕过前端限制的场景时mitmproxy这个基于Python的中间人代理工具能成为你的秘密武器。不同于Fiddler或Charles这类图形化工具mitmproxy提供了完整的Python API允许你在测试流程中动态操控每一个网络请求。1. 为什么选择mitmproxy进行Selenium测试在自动化测试领域mitmproxy提供了三大不可替代的优势实时流量操控可以在测试运行时动态修改请求和响应无需停止测试流程深度集成能力作为Python工具可直接与pytest/unittest等测试框架共享上下文无头环境支持完美适配CI/CD环境中的无头浏览器测试场景对比常见抓包工具工具特性Fiddler/Charlesmitmproxy脚本化控制有限完全支持无头环境兼容性较差优秀定制化程度中等极高性能开销较高较低提示当测试需要模拟慢速网络时mitmproxy可以通过延迟响应实现更真实的测试场景2. 核心配置让Selenium流量经过mitmproxy正确配置代理是使用mitmproxy的第一步以下是三种不同精度的配置方案2.1 全局代理配置适合调试from selenium import webdriver options webdriver.ChromeOptions() options.add_argument(--proxy-server127.0.0.1:8080) driver webdriver.Chrome(optionsoptions)这种配置简单直接但会影响所有流量包括测试框架自身的API调用。2.2 精细化代理控制推荐方案from selenium.webdriver.common.proxy import Proxy, ProxyType proxy Proxy({ proxyType: ProxyType.MANUAL, httpProxy: 127.0.0.1:8080, sslProxy: 127.0.0.1:8080, noProxy: localhost,127.0.0.1 # 排除内部请求 }) capabilities webdriver.DesiredCapabilities.CHROME proxy.add_to_capabilities(capabilities) driver webdriver.Chrome(desired_capabilitiescapabilities)2.3 多代理环境配置当需要同时监控多个浏览器实例时from selenium import webdriver from selenium.webdriver.common.proxy import Proxy def create_driver_with_proxy(port): proxy Proxy({ proxyType: MANUAL, httpProxy: f127.0.0.1:{port}, sslProxy: f127.0.0.1:{port} }) capabilities webdriver.DesiredCapabilities.CHROME proxy.add_to_capabilities(capabilities) return webdriver.Chrome(desired_capabilitiescapabilities) # 启动两个使用不同代理端口的浏览器 driver1 create_driver_with_proxy(8080) # mitmproxy实例1 driver2 create_driver_with_proxy(8081) # mitmproxy实例23. 解决HTTPS流量捕获的证书问题即使配置了代理HTTPS网站仍可能出现安全警告。以下是系统化的解决方案3.1 安装mitmproxy根证书# 生成证书存放目录 mkdir -p ~/.mitmproxy # 启动mitmproxy自动生成证书 mitmdump killall mitmdump # 生成后立即停止 # 将证书安装到系统信任库 certutil -d sql:$HOME/.pki/nssdb -A -t C,, -n mitmproxy -i ~/.mitmproxy/mitmproxy-ca-cert.pem3.2 Selenium自动信任证书对于ChromeDriver可通过以下参数自动接受不安全证书options webdriver.ChromeOptions() options.add_argument(--ignore-certificate-errors) options.add_argument(--allow-running-insecure-content) options.add_argument(--disable-web-security) driver webdriver.Chrome(optionsoptions)3.3 针对Firefox的特殊配置profile webdriver.FirefoxProfile() profile.accept_untrusted_certs True profile.assume_untrusted_cert_issuer False driver webdriver.Firefox(firefox_profileprofile)4. 实战动态修改API响应mitmproxy的真正威力在于其脚本化控制能力。创建一个addon.py文件from mitmproxy import http def response(flow: http.HTTPFlow) - None: # 修改特定API的响应 if api/v1/user in flow.request.url: original_json flow.response.json() original_json[username] test_user flow.response.text str(original_json) # 注入测试标记 if flow.response.headers.get(content-type, ).startswith(text/html): html flow.response.text html html.replace(/body, scriptwindow.__TEST_MODE__true;/script/body) flow.response.text html启动mitmproxy加载脚本mitmweb -s addon.py常见响应修改场景Mock数据替换API返回的测试数据错误注入模拟服务器错误响应功能开关修改前端配置标记性能测试延迟特定资源加载5. 高级技巧与疑难解决5.1 处理WebSocket流量mitmproxy同样支持WebSocket流量监控和修改def websocket_message(flow: http.HTTPFlow): if flow.websocket and chat in flow.request.url: last_message flow.websocket.messages[-1] if bpassword in last_message.content: last_message.content last_message.content.replace( bpassword123456, bpassword****** )5.2 性能优化配置当处理大量请求时调整以下参数class MyAddon: def load(self, loader): loader.add_option( namestream_large_bodies, typespecstr, default1m, helpStream data larger than this size ) def running(self): print(f当前性能配置{ctx.options.stream_large_bodies})5.3 常见问题排查流量未经过代理检查浏览器是否配置了其他代理扩展验证chrome://net-internals/#proxy的实际代理设置HTTPS网站无法加载确认证书已正确安装检查是否开启了--ignore-certificate-errors修改响应未生效确保脚本没有语法错误检查URL匹配逻辑是否准确6. 测试场景实战案例6.1 A/B测试验证def response(flow): if flow.request.url.endswith(/experiment/variant): flow.response.text {variant: B}6.2 地理围栏测试def response(flow): if geo-api in flow.request.url: flow.response.text {country: US, region: CA}6.3 性能基准测试import time def request(flow): if critical-api in flow.request.url: flow.request.headers[X-Start-Time] str(time.time()) def response(flow): if critical-api in flow.request.url: start float(flow.request.headers[X-Start-Time]) latency time.time() - start print(fAPI响应延迟{latency:.2f}s)在持续集成环境中建议将mitmproxy作为fixture管理import pytest from mitmproxy.tools.main import mitmdump pytest.fixture(scopesession) def proxy_server(): process mitmdump([-s, addon.py, --listen-port, 8080]) yield process.terminate()这种深度集成方式让网络操控成为自动化测试的自然组成部分而非外部依赖。当测试需要验证极端网络条件时mitmproxy提供的--set connection_strategylazy等参数可以模拟各种网络异常情况。

更多文章