Selenium-wire无法监控Chromium的localhost请求解决方案
问题背景
- 尝试使用selenium-wire拦截Chromium浏览器发起的localhost请求,但工具始终无法检测到这类请求
- 核心需求:监控浏览器中
http://localhost:3000/media/filename.mp4格式的本地视频文件请求,当响应状态码为400(视频资源不存在/加载失败)时自动刷新页面 - 已确认localhost请求确实在浏览器中正常发起:

原有实现代码如下:
import time from selenium.common.exceptions import WebDriverException from seleniumwire import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option( "debuggerAddress", "127.0.0.1:9222" ) # 控制已存在的Chromium会话 sw_options = {"port": 12345} # selenium-wire连接已有会话的必填参数 try: driver = webdriver.Chrome( executable_path="./chromedriver", chrome_options=chrome_options, seleniumwire_options=sw_options, ) driver.get( "https://www.google.com" ) # 访问公网地址时可以正常捕获请求,访问localhost地址时无法捕获 while True: for request in driver.requests: if request.response: if request.response.status_code == 206: print(request.url, request.response.status_code, "Error") driver.refresh() time.sleep(5) except WebDriverException as exc: print(exc.msg)
- 现象:访问公网页面时selenium-wire可以正常捕获请求,但所有发往localhost的请求都无法被捕获。
问题原因
selenium-wire默认配置下,会将localhost、127.0.0.1等本地地址加入代理绕过列表,发往这些地址的请求不会经过selenium-wire的内置代理,因此无法被捕获。如果是手动启动Chromium再通过debugger地址连接的场景,浏览器启动时默认的代理绕过规则也会进一步导致本地请求不经过selenium-wire代理。
解决方案
方案1:修改selenium-wire配置,放行本地请求捕获
修改seleniumwire_options配置,清空默认的主机排除列表,关闭本地地址代理绕过:
sw_options = { "port": 12345, # 清空默认排除的主机列表,不跳过任何地址的请求捕获 "exclude_hosts": [], # 配置代理规则,不绕过localhost/127.0.0.1的请求 "proxy": { "no_proxy": "" } }
注意:如果使用连接已有Chromium会话的模式,启动Chromium时不能添加
--proxy-bypass-list=<-loopback>参数,否则本地请求仍会绕过代理,导致捕获失败。优先使用selenium-wire直接启动浏览器实例的模式,代理配置会自动生效,稳定性更高。
方案2:不依赖网络拦截,通过前端API检测视频加载状态(推荐)
如果核心需求只是检测视频加载失败后刷新页面,完全不需要拦截网络请求,通过浏览器原生API检测视频状态的方案更稳定,不受代理配置影响:
import time from selenium.common.exceptions import WebDriverException from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") try: driver = webdriver.Chrome( executable_path="./chromedriver", chrome_options=chrome_options, ) while True: # 检测是否存在视频加载400错误 has_400_error = driver.execute_script(""" // 通过Performance API获取所有资源加载记录 const resources = performance.getEntriesByType('resource'); for (const res of resources) { // 匹配视频资源路径,检测响应状态码 if (res.name.includes('/media/') && res.responseStatus === 400) { return true; } } // 兜底检测video标签的加载错误状态 const videos = document.querySelectorAll('video'); for (const v of videos) { if (v.networkState === HTMLMediaElement.NETWORK_NO_SOURCE) { return true; } } return false; """) if has_400_error: print("检测到视频资源加载失败,刷新页面") driver.refresh() # 刷新后清空已有资源记录,避免重复触发 driver.execute_script("performance.clearResourceTimings()") time.sleep(5) time.sleep(1) except WebDriverException as exc: print(exc.msg)
该方案不需要依赖selenium-wire的请求拦截能力,直接从浏览器上下文获取资源加载状态,不会出现本地请求捕获不到的问题,适配所有地址的资源检测场景。
内容的提问来源于stack exchange,提问作者juanmac
相关产品推荐
相关产品推荐

