【问题标题】:How to produce custom JSON output from Scrapy?如何从 Scrapy 生成自定义 JSON 输出?
【发布时间】:2018-05-02 20:08:08
【问题描述】:

我正在编写一个 Scrapy 脚本,它的输出应该如下:

{
  "state": "FL",
  "date": "2017-11-03T14:52:26.007Z",
  "games": [
    {
      "name":"Game1"
    },
    {
      "name":"Game2"
    }
  ]
}

但对我来说,当我运行scrapy crawl items -o data.json -t json 时,它的效果如下。 state的重复

[
{"state": "CA", "games": [], "crawlDate": "2014-10-04"},
{"state": "CA", "games": [], "crawlDate": "2014-10-04"},
]

代码如下:

导入scrapy

items.py

class Item(scrapy.Item):
 state = scrapy.Field()
 games = scrapy.Field()

在 Spider 文件中,item 类被称为:

item = Item()
item['state'] = state
item['Date'] = '2014-10-04'
item['games'] = games

我知道这不是完整的代码,但它应该让我了解我的全部内容。

【问题讨论】:

    标签: python json


    【解决方案1】:

    参考。 https://stackoverflow.com/a/43698923/8964297

    您可以尝试像这样编写自己的管道:

    将此放入您的pipelines.py 文件中:

    import json
    
    
    class JsonWriterPipeline(object):
        def open_spider(self, spider):
            self.file = open('scraped_items.json', 'w')
            # Your scraped items will be saved in the file 'scraped_items.json'.
            # You can change the filename to whatever you want.
            self.file.write("[")
    
        def close_spider(self, spider):
            self.file.write("]")
            self.file.close()
    
        def process_item(self, item, spider):
            line = json.dumps(
                dict(item),
                indent = 4,
                sort_keys = True,
                separators = (',', ': ')
            ) + ",\n"
            self.file.write(line)
            return item
    

    然后修改您的settings.py 以包含以下内容:

    ITEM_PIPELINES = {
        'YourSpiderName.pipelines.JsonWriterPipeline': 300,
    }
    

    YourSpiderName 更改为您的蜘蛛的正确名称。

    请注意,文件由管道直接写入,因此您不必使用-o-t 命令行参数指定文件和格式。

    希望这能让你更接近你所需要的。

    【讨论】:

    • 获取项目后是否会运行? scraped_items.json 是什么?
    • @Volatil3, 每一个获取到的项目都会触发管道,并将其写入 JSON 文件。 scraped_items.json 是输出文件的名称。您可以将文件名(和路径)更改为您喜欢的任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    相关资源
    最近更新 更多