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格式的文件.好处是每次数据都直接存到磁盘文件中,不会耗内存,数据相对安全.

  • 相关阅读:
    hdu 5119 Happy Matt Friends
    hdu 5128 The E-pang Palace
    hdu 5131 Song Jiang's rank list
    hdu 5135 Little Zu Chongzhi's Triangles
    hdu 5137 How Many Maos Does the Guanxi Worth
    hdu 5122 K.Bro Sorting
    Human Gene Functions
    Palindrome(最长公共子序列)
    A Simple problem
    Alignment ( 最长上升(下降)子序列 )
  • 原文地址:https://www.cnblogs.com/weiwei2016/p/10516457.html
Copyright © 2011-2022 走看看