在Scrapy中,所有item数据都会通过pipelines进行处理,想要保存为json格式文件,只需要在piplines中进行相应的处理即可。

1、使用系统模块导出json

from scrapy.exporters import JsonItemExporter

class JsonExporterPipeline(object):

def __init__(self):

self.file = open('articlejson.json', 'wb')

self.exporter = JsonItemExporter(self.file, encoding="utf-8", ensure_ascii=False)

self.exporter.start_exporting()

def close_spider(self, spider):

self.exporter.finish_exporting()

self.file.close()

def process_item(self, item, spider):

self.exporter.export_item(item)

return item

2、自定义

在pipelines.py中加入以下代码

import codecs

import json

class JsonWithEncodingPipeline(object):

def __init__(self):

self.file = codecs.open('article.json', 'w', encoding='utf-8')

def process_item(self, item, spider):

lines = json.dumps(dict(item), ensure_ascii=False) + "\n"

self.file.write(lines)

return item

def spider_closed(self, spider):

self.file.close()

说明:

codecs 避免打开文件时出现编码错误。

json.dumps : dict转成str

json.loads: str转成dict

ensure_ascii=False: 避免处理英文以外语言时出错

return item:交给下一个pipeline处理

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐