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

SeleniumWire中response.reason为空:状态码正常但原因值缺失

解决SeleniumWire中response.reason为空的问题

使用SeleniumWire的响应拦截器时,能正常获取响应状态码,但response.reason字段始终为空,导致无法输出类似200 (OK)的带状态原因格式,实际只能得到200 ()。

解决方法

部分场景下SeleniumWire无法从响应中解析出状态原因短语,我们可以手动维护一个HTTP状态码与对应原因的映射表,通过状态码匹配获取对应的原因:

from seleniumwire import webdriver 

# 定义常用HTTP状态码与原因短语的映射
HTTP_STATUS_REASONS = {
    200: 'OK',
    201: 'Created',
    400: 'Bad Request',
    401: 'Unauthorized',
    403: 'Forbidden',
    404: 'Not Found',
    500: 'Internal Server Error',
    502: 'Bad Gateway',
    # 可根据需求扩展更多状态码
}

user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/112.0'

def my_response_interceptor(request, response): 
    # 从映射表中获取对应原因,无匹配则返回空字符串
    reason = HTTP_STATUS_REASONS.get(response.status_code, '')
    print(f"status: {response.status_code} ({reason})")
    print(response.headers)

options = webdriver.FirefoxOptions()
options.set_preference("general.useragent.override", user_agent)

driver = webdriver.Firefox(options=options)
driver.response_interceptor = my_response_interceptor

driver.maximize_window()
driver.get('site')

补充说明

如果业务中涉及更多不常见的HTTP状态码,可以参考HTTP标准规范扩展HTTP_STATUS_REASONS字典,确保所有需要的状态码都能匹配到对应的原因短语。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:10:04