在scrapy中,将item存入json文件

两种方法将item写入json文件,一种是自定义写入,一种是利用scrapy本身的scrapy.exports中提供的导出方式,scrapy提供的导出方式有:

['BaseItemExporter', 'PprintItemExporter', 'PickleItemExporter',
           'CsvItemExporter', 'XmlItemExporter', 'JsonLinesItemExporter',
           'JsonItemExporter', 'MarshalItemExporter']

方法一:自己写的json导出

 

假设将item存入article.json

首先在pipeline中进行设置:

import codecs
import json

class JsonWithEncodingPipeline(object):
    #自定义json文件的导出
    def __init__(self):#初始化,打开文件
        self.file = codecs.open('article.json', 'w', encoding="utf-8")
        #这里用codecs库来打开文件,目的是编码不会出错


    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()

然后在settings中,把这个pipeline开启即可。

 

方法二:利用系统自带的JsonItemExport

假设将item存入articleexport.json中

 

from scrapy.exporters imort JsonItemExporter
class JsonExporterPipleline(object):  # 调用scrapy提供的json export导出json文件 
    def __init__(self): 
        self.file = open('articleexport.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

然后在settings中,把这个pipeline开启即可。

注意:方法二导出的json文件中,内容是一个列表list[]  。方法一的方式则是字典{}。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值