Scrapy之自定义Pipeline输出json文件

自定义Pipeline输出json文件

代码

class JsonWithEncodingPipeline(object):
    #自定义json文件的导出
    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()

写好pipeline后记得在settings中将这个pipeline设置进去。

测试代码

def test_to_json():
    import codecs
    import json
    # 自定义json文件的导出
    file = codecs.open('test.json', 'w', encoding="utf-8")
    item = {'张三': 32, 'Jim': 23, 'Bob': 53}
    # lines = json.dumps(item, ensure_ascii=False) + "\n"
    lines = json.dumps(item) + "\n"
    file.write(lines)
    file.close()

测试结果

数据:{‘张三’: 32, ‘Jim’: 23, ‘Bob’: 53}
lines = json.dumps(item,ensure_ascii=False) + “\n”

  1. 添加参数ensure_ascii=False:
    输出本地文件test.json: {“张三”: 32, “Jim”: 23, “Bob”: 53}
  2. 不添加参数ensure_ascii=False:
    输出本地文件test.json: {"\u5f20\u4e09": 32, “Jim”: 23, “Bob”: 53}

测试分析

json.dumps()将python数据序列化到本地过程中,默认使用ascii编码格式,中文如果想正常导出,则需要添加参数:ensure_ascii=False,取消ascii默认编码方式。

json包

参考Python 标准库-json

里面有对json库的使用说明。

  1. json.loads():字符串–>python基本数据类型
  2. json.dumps():python基本数据类型–>字符串
  3. json.load():文件–>python基本数据类型
  4. json.dump():python基本数据类型–>文件

利用Scrapy提供的JsonItemExporter类保存json数据

示例代码

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

总结

使用JsonItemExporter对象前需要先实例化该对象以及其参数,使用过程中需要有以下步骤:

  1. 调用方法start_exporting()以标识exporting过程的开始。
  2. 对要导出的每个项目调用export_item()方法。
  3. 最后调用finish_exporting()表示exporting过程的结束。

参考链接

Scrapy——Item Exporters

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值