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

继承式Scrapy爬虫无输出文件内容问题排查求助

问题分析与解决

为什么生成两个JSON文件?

你运行爬虫时大概率用了scrapy crawl myspecificspider -o myspecificspider.json这类命令,触发了Scrapy内置的Feed导出功能,生成myspecificspider.json;同时自定义的JsonPipeline会生成{spider.name}_items.json,所以出现两个文件。如果只想要后者,运行时去掉-o参数即可,或者在爬虫的custom_settings里禁用Feed导出:

custom_settings = {
    'ITEM_PIPELINES': {'my_spiders.pipelines.JsonPipeline': 300,},
    'FEEDS': {}  # 关闭内置Feed导出
}

为什么两个文件都为空?

结合你的代码,从以下几个点排查修复:

1. 修复Pipeline的写入逻辑

当前JsonPipeline没有做内容刷新,可能导致爬虫结束前内容没写入文件。修改代码,确保写入后立即刷新,同时加上编码和中文转义处理:

class JsonPipeline:
    def open_spider(self, spider):
        filename = f'{spider.name}_items.json'
        self.file = open(filename, 'w', encoding='utf-8')  # 指定编码避免乱码
    def close_spider(self, spider):
        self.file.flush()  # 关闭前强制刷新
        self.file.close()
    def process_item(self, item, spider):
        # 禁用ASCII转义,保证中文正常显示
        line = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(line)
        self.file.flush()  # 每次写入后刷新
        return item

2. 确认Pipeline是否正常启用

检查BaseSpider中的custom_settings路径是否正确。如果你的项目结构是标准Scrapy结构(my_spiders/my_spiders/pipelines.py),'my_spiders.pipelines.JsonPipeline'是正确的。如果不确定,可以在MySpecificSpider中显式重写custom_settings,确保配置生效:

class MySpecificSpider(BaseSpider):
    name = 'myspecificspider'
    start_urls = ['https://quotes.toscrape.com']
    allowed_domains = ['quotes.toscrape.com']
    debug = False
    # 显式指定配置,避免继承可能的问题
    custom_settings = {
        'ITEM_PIPELINES': {'my_spiders.pipelines.JsonPipeline': 300,},
        'LOG_LEVEL': 'DEBUG',  # 开启DEBUG日志,方便排查请求和Item处理情况
        'FEEDS': {}
    }

3. 排查请求与Item生成流程

  • 确认parse方法中打印的listing_url正常输出,说明请求已发出。开启DEBUG日志后,可以查看这些请求的响应状态码,确认是否成功抓取。
  • 确认parse_object方法中打印的Extracted Item正常输出,说明Item已生成。如果这两步都有输出,那问题肯定出在Pipeline的写入环节,按步骤1修复即可。

4. 检查继承逻辑的潜在冲突

BaseSpider中的空parse方法不影响子类,因为MySpecificSpider已经重写了该方法。如果全局settings.py中配置了其他Pipeline,会和custom_settings合并,但custom_settings优先级更高,无需担心冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:24:53