【问题标题】:scrapy:custom pipeline save file with spider namescrapy:带有蜘蛛名称的自定义管道保存文件
【发布时间】:2014-09-18 08:05:09
【问题描述】:

这是一个自定义管道
并且我想用蜘蛛名称保存文件
这是我的代码。它将创建一个 json 文件但只保存一个数据
请教我如何编辑代码。里面应该有10个数据。

 class JsonWithEncodingPipeline(object):
    # def __init__(self):
    #save file with fixed name
    # self.file = codecs.open('outputbytest.json ', 'w', encoding='utf-8')

    def process_item(self, item, spider):
    #How to save file with dynamic name??
    self.file = codecs.open('%s_outputchiness.json' % spider.name, 'w', encoding='utf-8')

    line = json.dumps(dict(item)) + "\n"   
    self.file.write(line.encode('utf-8').decode("unicode_escape"))
    return item  
    def spider_closed(self, spider):
        self.file.close()

【问题讨论】:

    标签: python-2.7 scrapy json


    【解决方案1】:

    使用'w' 参数打开文件会覆盖现有内容。你应该做的是打开open_spider下的文件,这样它只会打开一次,而不是每次你写一个项目。

    def open_spider(self, spider):
        self.file = codecs.open('%s_outputchiness.json' % spider.name, 'w', encoding='utf-8')
    
    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + "\n"   
        self.file.write(line.encode('utf-8').decode("unicode_escape"))
    
    def spider_closed(self, spider):
        self.file.close()
    

    如果您希望每次运行蜘蛛时都使用不同的文件名,我建议在名称中包含当前日期和时间。

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 2015-11-07
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多