【问题标题】:Export scraping data in multiple formats using scrapy使用 scrapy 以多种格式导出抓取数据
【发布时间】:2015-06-24 16:42:52
【问题描述】:

我正在抓取一个网站以将数据导出为语义格式 (n3)。 不过,我还想对该数据进行一些数据分析,因此将其保存为 csv 格式会更方便。

我可以同时获取两种格式的数据

scrapy spider -t n3 -o data.n3
scrapy spider -t csv -o data.csv

但是,这会抓取两次数据,我无法承受大量数据。

有没有办法将相同的抓取数据导出为多种格式?(无需多次下载数据)

我发现有一个可以导出为不同格式的抓取数据的中间表示很有趣。但是用scrapy似乎没有办法做到这一点。

【问题讨论】:

标签: python web-scraping scrapy exporter


【解决方案1】:

根据我在浏览源代码和文档后的理解,-t option refers to the FEED_FORMAT setting 不能有多个值。此外,FeedExporter 内置扩展 (source) 仅适用于单个导出器。

实际上,考虑在Scrapy Issue Tracker 提出功能请求

更像是一种解决方法,定义一个管道并开始使用多个导出器导出。例如,这里是如何导出为 CSV 和 JSON 格式:

from collections import defaultdict

from scrapy import signals
from scrapy.exporters import JsonItemExporter, CsvItemExporter


class MyExportPipeline(object):
    def __init__(self):
        self.files = defaultdict(list)

     @classmethod
     def from_crawler(cls, crawler):
         pipeline = cls()
         crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
         crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
         return pipeline

    def spider_opened(self, spider):
        csv_file = open('%s_products.csv' % spider.name, 'w+b')
        json_file = open('%s_products.json' % spider.name, 'w+b')

        self.files[spider].append(csv_file)
        self.files[spider].append(json_file)

        self.exporters = [
            JsonItemExporter(json_file),
            CsvItemExporter(csv_file)
        ]

        for exporter in self.exporters:
            exporter.start_exporting()

    def spider_closed(self, spider):
        for exporter in self.exporters:
            exporter.finish_exporting()

        files = self.files.pop(spider)
        for file in files:
            file.close()

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

【讨论】:

  • 好的,这是合适的解决方案,尽管我希望能够使用参数配置整个导出。这样,我只能编辑settings.py来更改导出配置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多