python - Scrapy:如何将爬取统计信息保存到 json 文件中?
问题描述
在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 文件?
解决方案
您可以使用在运行结束时运行的统计信息收集器。
将其添加到 settings.py:
STATS_CLASS = 'mycrawler.MyStatsCollector.MyStatsCollector'
这是将 JSON 输出到文件的 MyStatsCollector.py 的基本实现:
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)