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

Scrapy中如何将scrapy.http.headers.Headers转为字符串及JSON格式

解决Scrapy Headers转字符串和JSON的问题

嘿,我来帮你搞定这两个Scrapy Headers的处理问题!你遇到的报错是因为Scrapy的Headers对象里的键和值都是bytes类型,而JSON序列化不支持bytes作为键,所以得先把这些bytes都解码成字符串才行。

一、把Headers类型转换为字符串

首先,我们可以先把Scrapy的Headers对象转换成普通的Python字典,然后将所有的bytes键和值解码成字符串,最后再转成字符串格式。这里有两种方式:

方式1:自定义函数处理

def headers_to_string(headers):
    str_headers = {}
    # 遍历Headers里的每个键值对
    for key, value_list in headers.items():
        # 把bytes类型的键解码成字符串
        str_key = key.decode('utf-8')
        # 把值列表里的第一个元素解码(大多数headers值只有一个元素)
        str_value = value_list[0].decode('utf-8')
        str_headers[str_key] = str_value
    # 转成字符串返回
    return str(str_headers)

在你的example方法里调用:

def example(self, response):
    headers_str = headers_to_string(response.headers)
    print(type(headers_str))
    print(headers_str)

方式2:用字典推导式简化代码

如果不想写函数,也可以直接用一行字典推导式处理:

def example(self, response):
    # 先转成纯字符串的字典
    str_headers_dict = {k.decode('utf-8'): v[0].decode('utf-8') for k, v in response.headers.items()}
    # 再转成字符串
    headers_str = str(str_headers_dict)
    print(headers_str)

二、把Headers转为JSON格式

同样的思路,先把Headers对象转换成纯字符串的字典,再用json.dumps序列化。

完整代码示例

import json

def headers_to_json(headers):
    str_headers = {}
    for key, value_list in headers.items():
        str_key = key.decode('utf-8')
        # 如果值列表有多个元素,就全部解码;否则取第一个
        str_values = [val.decode('utf-8') for val in value_list]
        str_headers[str_key] = str_values[0] if len(str_values) == 1 else str_values
    # 序列化并返回JSON字符串,indent=2让格式更美观
    return json.dumps(str_headers, indent=2)

def example(self, response):
    try:
        headers_json = headers_to_json(response.headers)
        print(headers_json)
    except Exception as e:
        print(f"转JSON出错:{e}")

简化版(字典推导式)

import json

def example(self, response):
    str_headers_dict = {k.decode('utf-8'): v[0].decode('utf-8') for k, v in response.headers.items()}
    headers_json = json.dumps(str_headers_dict, indent=2)
    print(headers_json)

这样处理后,就不会再出现TypeError: keys must be str, int, float, bool or None, not bytes的报错了,因为所有的bytes都已经转成了字符串类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:49:11