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

Python requests检测Content-Length触发KeyError问题排查

问题根因

你遇到的KeyError: 'content-length'报错,核心是两个逻辑错误:

  1. 字典取值逻辑顺序错了:你直接用response.headers['Content-Length']取值的写法,只要头字段不存在,会直接抛出键不存在的异常,根本走不到后面判断是否为None的逻辑。
  2. 你确认目标返回Content-Length但仍报错,大概率是遇到了使用Transfer-Encoding: chunked分块传输的响应,按照HTTP协议规范,这类响应不会携带Content-Length头,属于正常情况。

requests的响应头是大小写不敏感的字典,不管你写Content-Length还是content-length都能匹配到,但前提是这个字段真实存在。

正确判断头字段是否存在的写法

两种通用写法都不会触发KeyError:

  • 方法1:先用in关键字做存在性校验,确认字段存在后再取值,逻辑最直观
  • 方法2:用字典自带的.get(key, default)方法取值,字段不存在时会返回你指定的默认值(不指定默认返回None),不会触发异常
修正后的符合需求的完整代码
import requests

# 读取IP列表文件名
file_name = input("Enter the name of the file: ")

with open(file_name, 'r') as f:
    for line in f:
        ip = line.strip()
        # 跳过空行
        if not ip:
            print("No host supplied, skip empty line")
            continue
        url = f"http://{ip}/"
        print(f"\nProcessing target: {ip}")
        try:
            # 加超时避免请求卡死,可根据实际场景调整超时时间、是否允许重定向
            response = requests.get(url, timeout=10, allow_redirects=False)
            # 先判断Content-Length是否存在,不存在直接跳过当前IP
            if 'Content-Length' not in response.headers:
                print("No Content-Length header found, skip current target")
                continue
            # 输出要求的三类信息
            print(f"Status Code: {response.status_code}")
            # Server头也可能缺失,用get取值避免触发报错
            print(f"Server Header: {response.headers.get('Server', 'Not Provided')}")
            print(f"Content-Length: {response.headers['Content-Length']}")
        except Exception as e:
            print(f"Request failed for {ip}: {str(e)}")
            continue

代码额外增加了请求异常捕获、超时配置、空行跳过、Server头缺失兼容处理,避免运行过程中因为网络不通、个别头缺失直接崩溃。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 23:21:49