我正在尝试更改 Scrapy 的统计中间件。
这是 Scrapy 的 stats.py 完整内容:
from scrapy.exceptions import NotConfigured
from scrapy.utils.request import request_httprepr
from scrapy.utils.response import response_httprepr
class DownloaderStats(object):
def __init__(self, stats):
self.stats = stats
@classmethod
def from_crawler(cls, crawler):
if not crawler.settings.getbool('DOWNLOADER_STATS'):
raise NotConfigured
return cls(crawler.stats)
def process_request(self, request, spider):
self.stats.inc_value('downloader/request_count', spider=spider)
self.stats.inc_value('downloader/request_method_count/%s' % request.method, spider=spider)
reqlen = len(request_httprepr(request))
self.stats.inc_value('downloader/request_bytes', reqlen, spider=spider)
def process_response(self, request, response, spider):
self.stats.inc_value('downloader/response_count', spider=spider)
self.stats.inc_value('downloader/response_status_count/%s' % response.status, spider=spider)
reslen = len(response_httprepr(response))
self.stats.inc_value('downloader/response_bytes', reslen, spider=spider)
return response
def process_exception(self, request, exception, spider):
ex_class = "%s.%s" % (exception.__class__.__module__, exception.__class__.__name__)
self.stats.inc_value('downloader/exception_count', spider=spider)
self.stats.inc_value('downloader/exception_type_count/%s' % ex_class, spider=spider)
在 from_crawler
类方法中,传入的到底是什么?
首先,DownloaderStats(object)
并不意味着 DownloaderStats 正在传递一个对象,它意味着 DownloaderStats 类扩展了 object
类。
在你的类方法中,cls
是被调用的类,在本例中 DownloaderStats
。所以代码cls(crawler.stats)
可以被认为是 DownloaderStats(crawler.stats)
,它实例化 DownloaderStats 类的对象。在 Python 中实例化对象会导致它们 __init__
被调用的方法,所以crawler.stats
的值被分配给stats
__init__
的参数方法,然后将其分配给 self.stats
.
我是一名优秀的程序员,十分优秀!