【问题标题】:Can't get Scrapy Stats from scrapy.CrawlerProcess无法从 scrapy.CrawlerProcess 获取 Scrapy Stats
【发布时间】:2019-04-13 08:53:18
【问题描述】:

我正在从另一个脚本运行 scrapy 蜘蛛,我需要从 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

我希望统计信息包含这条数据(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)}

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

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

最好, 彼得

【问题讨论】:

    标签: python web-scraping scrapy web-crawler scrapy-spider


    【解决方案1】:

    根据the documentationCrawlerProcess.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
    

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多