如何使用 Scrapy Items 并以 json 格式存储输出?

How to use Scrapy Items and store output in json format?

我试图让我的输出看起来像下面的 json 格式。

[{"title": "Test", "kategorie": "abc", "url": "www.url.com"},
{"title": "Test", "kategorie": "xyz", "url": "www.url.com"},
{"title": "Test", "kategorie": "sca", "url": "www.url.com"}]

但是在使用 Items 之后,我看到了一些值,但并不是所有值都存储在列表中:

[{"title": ["Test"], "kategorie": ["abc"], "url": "www.url.com"},
{"title": ["Test"], "kategorie": ["xyz"], "url": "www.url.com"},
{"title": ["Test"], "kategorie": ["sca"], "url": "www.url.com"}]

这是我的items.py

class MyItem(scrapy.Item):
    title = scrapy.Field()
    kategorie = scrapy.Field()
    url = scrapy.Field()

这是我的 pipelines.py,已在 settings.py 中启用。

class MyPipeline(object):

    file = None

    def open_spider(self, spider):
        self.file = open('item.json', 'wb')
        self.exporter = JsonItemExporter(self.file)
        self.exporter.start_exporting()

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

这是我spider.py中的解析方法。所有 xpath-methods return 一个已抓取值的列表。之后将它们放在一起并迭代创建一个字典,该字典最终将在导出文件中作为 json.

def parse(self, response):

   item = MyItem()

   title = response.xpath('//h5/text()').getall()
   kategorie = response.xpath('//span[@class="abc1"]//text()').getall()
   url = response.xpath('//div[@class="abc3"]//a/@href').getall()

   data = zip(title, kategorie, url)

   for i in data:
      item['title'] = i[0],
      item['kategorie'] = i[1],
      item['url'] = i[2]

      yield item

我是这样开始抓取过程的:

scrapy crawl spider_name

如果我不使用 Items 和 Pipelines,它可以正常使用:

scrapy crawl spider_name -o item.json

我想知道为什么有些值存储在列表中而另一些则没有。如果有人有方法那就太好了。

使用 scrapy FEEDSItem 您可以直接从解析方法中生成项目对象,而不需要先 pipelinesziping 列表。请参阅下面的示例

import scrapy

class MyItem(scrapy.Item):
    title = scrapy.Field()
    kategorie = scrapy.Field()
    url = scrapy.Field()

class SampleSpider(scrapy.Spider):
    name = 'sample'
    start_urls = ['https://brownfield24.com/grundstuecke']

    custom_settings = {
        "FEEDS": {
            "items.json":{
                "format": "json"
            }
        }
    }

    def parse(self, response):
        for property in response.xpath("//*[contains(@class,'uk-link-reset')]"):
            item = MyItem()
            item['title'] = property.xpath(".//h5/text()").get()
            item['url'] = property.xpath(".//a/@href").get()
            item['kategorie'] = property.xpath(".//div[@class='uk-card-body']/p/span/text()").get()

            yield item

运行 使用 scrapy crawl sample 的蜘蛛将获得以下输出。