如何在 Scrapy 蜘蛛上 运行 cProfiler

How to run cProfiler on Scrapy spider

我在Scrapy中有一个蜘蛛,我想检查瓶颈。我也有一些 classes 进入主 Spider class。我想使用 cProlifer 检查函数执行时间:

if __name__ == '__main__':
    import pstats
    import cProfile
    from pstats import SortKey

    cProfile.run("QuotesSpider(scrapy.Spider)", "output.dat")

    with open('output_time.txt', 'w') as f:
        p = pstats('output.dat', stream=f)
        p.sort_stats('time').print_stats()

    with open('output_calls.txt', 'w') as f :
        p = pstats('output.dat', stream=f)
        p.sort_stats('calls').print_stats()

其中 QuotesSpider(scrapy.Spider) 是蜘蛛 class。可以理解的是,当 运行 蜘蛛使用 scrapy crawl quotes 时,我得到以下错误:NameError: name 'QuotesSpider' is not defined.

如何正确地将cProfile 与Scrapy 集成?由于 Scrapy 的请求是异步的,cProfile 是解决这个问题的最佳方法吗?

它有点隐藏,但您实际上可以 运行 cProfile 使用命令行中的标准 scrapy 命令,例如使用上面的示例来获得灵感

scrapy crawl spider --profile output.dat

然后你就可以像上面那样分析输出了。