zoukankan      html  css  js  c++  java
  • JsonItemExporter和JsonLinesItemExporter保存数据

    JsonItemExporter方式保存数据

     1 # -*- coding: utf-8 -*-
     2 from scrapy.exporters import JsonItemExporter
     3 
     4 
     5 class DemoPipeline(object):
     6     def __init__(self):
     7         self.fp = open("duanzi.json", "wb")
     8         self.exporter = JsonItemExporter(self.fp, ensure_ascii=False, encoding='utf-8')
     9         self.exporter.start_exporting()
    10 
    11     def open_spider(self, spider):
    12         pass
    13 
    14     def process_item(self, item, spider):
    15         self.exporter.export_item(item)
    16         return item
    17 
    18     def close_spider(self, spider):
    19         self.exporter.finish_exporting()
    20         self.fp.close()

    或JsonLinesItemExporter保存数据

     1 # -*- coding: utf-8 -*-
     2 from scrapy.exporters import JsonLinesItemExporter
     3 
     4 
     5 class DemoPipeline(object):
     6     def __init__(self):
     7         self.fp = open("duanzi.json", "wb")
     8         self.exporter = JsonLinesItemExporter(self.fp, ensure_ascii=False, encoding='utf-8')
     9 
    10     def open_spider(self, spider):
    11         pass
    12 
    13     def process_item(self, item, spider):
    14         self.exporter.export_item(item)
    15         return item
    16 
    17     def close_spider(self, spider):
    18         self.fp.close()

    区别:

    JsonItemExporter:每次把数据添加到内存中,最后统一写入到磁盘文件中。好处是,存储的是一个满足json规则的数据。坏处是如果数据量比较大,那么比较耗内存。

    JsonLinesItemExporter:每次调用export_item的时候就把这个item存储到磁盘中.坏处是一个字典一行,整个文件不是一个满足json格式的文件.好处是每次数据都直接存到磁盘文件中,不会耗内存,数据相对安全.

  • 相关阅读:
    2019天梯赛训练1
    Python课程设计 搭建博客
    最容易理解的贪吃蛇小游戏
    数据结构-队列
    数据结构-堆栈(2)
    数据结构-堆栈(1)
    数据结构-线性表(3)
    数据结构-线性表(1)
    linux知识积累
    Maven学习笔记
  • 原文地址:https://www.cnblogs.com/weiwei2016/p/10516457.html
Copyright © 2011-2022 走看看