【问题标题】:Scrapy: How to save crawling statistics to json file?Scrapy:如何将爬取统计信息保存到 json 文件中?
【发布时间】:2020-04-24 07:04:56
【问题描述】:

在 scrapy 2.0.1 中,我正在将新数据写入 json 文件。在该过程结束时,我想附加scrapy统计信息。现在我知道有一个可用的scrapy stats 集合:

https://docs.scrapy.org/en/latest/topics/stats.html

所以正确的代码行可能是这一行:stats.get_stats()

结合:

class ExtensionThatAccessStats(object):

    def __init__(self, stats):
        self.stats = stats

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.stats)

我当前的管道如下所示:

class test_pipeline(object):

    file = None

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

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

我是 Python 新手。如何添加此功能以将统计信息附加到 json 文件中?

【问题讨论】:

  • 你应该可以在你的管道中使用from_crawler
  • @Gallaecio 你能进一步解释一下吗?我在close_spider方法中添加了:print(self.stats.get_stats()),但是没有任何效果。
  • 您应该能够将问题的__init__from_crawler 方法添加到您的管道类中,从而使self.stats 可用。
  • 嘿,你有没有设法将统计数据导出到 json?

标签: python scrapy


【解决方案1】:

您可以使用在运行结束时运行的统计信息收集器。

将其添加到 settings.py:

STATS_CLASS = 'mycrawler.MyStatsCollector.MyStatsCollector'

下面是 MyStatsCollector.py 的基本实现,它将 JSON 输出到文件:

from scrapy.statscollectors import StatsCollector
from scrapy.utils.serialize import ScrapyJSONEncoder

class MyStatsCollector(StatsCollector):
    def _persist_stats(self, stats, spider):
        encoder = ScrapyJSONEncoder()
        with open("stats.json", "w") as file:
            data = encoder.encode(stats)
            file.write(data)

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2016-01-19
    • 1970-01-01
    相关资源
    最近更新 更多