如何在Scrapy中访问特定统计数据(“finish_reason”,“elapsed_time_seconds”)?

问题描述 投票:0回答:1

我正在使用 Scrapy,我可以用它从不同的 URL 抓取数据。我试图获得的一件事是统计数据,特别是

finish_reason
elapsed_time_seconds

我的

testspider.py
的结构看起来很标准:

class TestSpider(scrapy.Spider):

    name = 'testspider'
    def parse(self, response):
      ...
    reason = self.crawler.stats.get_value('finish_reason')
    print(reason)
    print(self.crawler.stats.get_value('elapsed_time_seconds'))
    print(self.crawler.stats.get_value('log_count/DEBUG'))

输出如下

...
None # finish_reason
None # elapsed_time_seconds
75   # log_count/DEBUG
2024-02-26 16:03:03 [scrapy.core.engine] INFO: Closing spider (finished)
2024-02-26 16:03:03 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 3039,
 'downloader/request_count': 4,
 'downloader/request_method_count/GET': 4,
 'downloader/response_bytes': 126947,
 'downloader/response_count': 4,
 'downloader/response_status_count/200': 4,
 'elapsed_time_seconds': 0.964805,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2024, 2, 26, 15, 3, 3, 840387, tzinfo=datetime.timezone.utc),
 'httpcompression/response_bytes': 639395,
 'httpcompression/response_count': 4,
 'item_scraped_count': 68,
 'log_count/DEBUG': 75,
 'log_count/INFO': 10,
 'memusage/max': 63651840,
 'memusage/startup': 63635456,
 'request_depth_max': 2,
 'response_received_count': 4,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/200': 1,
 'scheduler/dequeued': 3,
 'scheduler/dequeued/memory': 3,
 'scheduler/enqueued': 3,
 'scheduler/enqueued/memory': 3,
 'start_time': datetime.datetime(2024, 2, 26, 15, 3, 2, 875582, tzinfo=datetime.timezone.utc)}
2024-02-26 16:03:03 [scrapy.core.engine] INFO: Spider closed (finished)

我无法从

def parse
方法访问某些字段,可能是因为脚本仍在运行?我该如何实现这一目标?我想直接访问
Scrapy stats
中的数据并将其“手动”保存到数据库(我正在
pipeline.py
中执行此操作)。我如何实现这一目标?

python scrapy
1个回答
0
投票

这两个统计数据仅在引擎关闭期间设置,因此不可能将它们纳入回调中。您可以尝试手动订阅

spider_closed
信号,或者通过在蜘蛛中实现
closed
方法、管道中的
close_spider
方法等来订阅,但要注意当前未指定的信号执行顺序,因为统计数据您想要的也可以在
spider_closed
信号处理程序中设置。或者,您可以子类化
scrapy.extensions.corestats.CoreStats
scrapy.statscollectors.MemoryStatsCollector
以使您的代码更接近统计代码。

© www.soinside.com 2019 - 2024. All rights reserved.