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

Scrapy解析JSON触发TypeError:列表索引类型错误的解决方法

Scrapy爬取圣经注释时TypeError错误的解决办法

错误原因

TypeError: list indices must be integers or slices, not str 表明你在用字符串索引访问列表类型的数据。问题出在对返回JSON结构的判断有误:要么data本身是列表,要么data['0']对应的是列表(而非预期的字典),导致用字符串索引访问时触发错误。另外,yield from的用法也不对——它用于迭代生成器/可迭代对象,直接作用在_id字符串上会引发额外问题。

修正步骤与代码

  1. 先确认JSON结构:在parse方法中加入打印语句,查看API返回的实际数据层级(或用scrapy shell调试):
def parse(self, response):
    data = json.loads(response.body)
    print(data)  # 打印数据结构,确认层级关系
  1. 根据实际结构调整代码:
    假设API返回的data是一个列表,每个元素包含注释信息,修正后的代码如下:
import scrapy
import json

class catenaspider(scrapy.Spider):
    name = 'commentary'
    start_urls = ['https://api.catenabible.com:8080/anc_com/c/mt/1/1?tags=[%22ALL%22]&sort=def']

    def parse(self, response):
        data = json.loads(response.body)
        # 遍历列表中的每个注释项
        for comment_item in data:
            # 检查字段是否存在,避免KeyError
            if 'father' in comment_item and '_id' in comment_item['father']:
                # 以字典形式输出评论者ID
                yield {
                    'commenter_id': comment_item['father']['_id']
                }

如果实际结构是data['0']为列表,则调整遍历对象:

def parse(self, response):
    data = json.loads(response.body)
    # 遍历data['0']对应的列表
    for comment_item in data['0']:
        if 'father' in comment_item and '_id' in comment_item['father']:
            yield {
                'commenter_id': comment_item['father']['_id']
            }
  1. 注意事项:
  • 不要用yield from处理单个字符串字段,直接用yield输出字典即可;
  • 增加字段存在性检查,避免因API返回数据缺失字段导致的KeyError;
  • 若需要获取更多字段,可在yield的字典中添加对应键值对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:09:26