【问题标题】:scrapy set the output file in codescrapy 在代码中设置输出文件
【发布时间】:2014-04-29 11:18:52
【问题描述】:

我在 python 中使用 scrapy

我可以在cmd中设置输出json文件。但现在我需要在代码中做到这一点。

我试过这个:

在设置中

FEED_EXPORTERS = {
 'jsonlines': 'scrapy.contrib.exporter.JsonLinesItemExporter',
}
FEED_FORMAT = 'jsonlines'

在蜘蛛中

def __init(self):
    settings.overrides['FEED_URI'] = 'output.json'

注意

我正在开发一个简单的蜘蛛,所以我只需要Item Exporter,我不需要创建任何项目管道。

感谢您的帮助

【问题讨论】:

  • 有没有想过这个?
  • @Dagrooms 是的,我做过,但实际上我现在不记得了,因为我最终使用了一个管道,该管道将数据写入文件系统中的 JSON 文件和云上的数据库。
  • 没问题,我已经开始工作了,但我还是需要 xml 格式。

标签: python python-2.7 scrapy


【解决方案1】:

答案可以在 Scrapy 文档的示例中找到。可以通过编写正确的item pipeline 输出为任意格式,如下:

import json

class JsonWriterPipeline(object):

    def __init__(self):
        self.file = open('items.jl', 'wb')

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + "\n"
        self.file.write(line)
        return item

请注意,您还必须在默认的 Scrapy 项目设置文件中包含此管道。

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 2016-03-12
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多