无法从 scrapy.CrawlerProcess 获取 Scrapy Stats

Zx3*_*x3s 4 python web-crawler scrapy web-scraping scrapy-spider

我正在从另一个脚本运行爬虫蜘蛛,我需要从 Crawler 检索并保存到变量统计信息。我已经查看了文档和其他 StackOverflow 问题,但我无法解决这个问题。

这是我运行爬行的脚本:

import scrapy
from scrapy.crawler import CrawlerProcess


process = CrawlerProcess({})
process.crawl(spiders.MySpider)
process.start()

stats = CrawlerProcess.stats.getstats() # I need something like this
Run Code Online (Sandbox Code Playgroud)

我希望 stats 包含这条数据(scrapy.statscollectors):

     {'downloader/request_bytes': 44216,
     'downloader/request_count': 36,
     'downloader/request_method_count/GET': 36,
     'downloader/response_bytes': 1061929,
     'downloader/response_count': 36,
     'downloader/response_status_count/200': 36,
     'finish_reason': 'finished',
     'finish_time': datetime.datetime(2018, 11, 9, 16, 31, 2, 382546),
     'log_count/DEBUG': 37,
     'log_count/ERROR': 35,
     'log_count/INFO': 9,
     'memusage/max': 62623744,
     'memusage/startup': 62623744,
     'request_depth_max': 1,
     'response_received_count': 36,
     'scheduler/dequeued': 36,
     'scheduler/dequeued/memory': 36,
     'scheduler/enqueued': 36,
     'scheduler/enqueued/memory': 36,
     'start_time': datetime.datetime(2018, 11, 9, 16, 30, 38, 140469)}
Run Code Online (Sandbox Code Playgroud)

我已经检查了 CrawlerProcess,它在抓取过程完成后返回延迟并从其“爬虫”字段中删除爬虫。

有没有办法解决这个问题?

最好的,彼得

sta*_*ify 5

根据文档CrawlerProcess.crawl接受爬虫类或蜘蛛类,您可以通过CrawlerProcess.create_crawler.

因此,您可以在开始爬网过程之前创建爬虫实例,然后检索预期的属性。

下面我通过编辑几行原始代码为您提供了一个示例:

import scrapy
from scrapy.crawler import CrawlerProcess


class TestSpider(scrapy.Spider):
    name = 'test'
    start_urls = ['http://httpbin.org/get']

    def parse(self, response):
        self.crawler.stats.inc_value('foo')


process = CrawlerProcess({})
crawler = process.create_crawler(TestSpider)
process.crawl(crawler)
process.start()


stats_obj = crawler.stats
stats_dict = crawler.stats.get_stats()
# perform the actions you want with the stats object or dict
Run Code Online (Sandbox Code Playgroud)