scrapy的数据收集器可以实时记录爬虫状态数据,默认在爬虫结束是打印:
C:\Anaconda2\Lib\site-packages\scrapy\statscollectors.py
class StatsCollector(object):
def __init__(self, crawler):
self._dump = crawler.settings.getbool('STATS_DUMP')
self._stats = {}
......
def close_spider(self, spider, reason):
if self._dump:
logger.info("Dumping Scrapy stats:\n" + pprint.pformat(self._stats),
extra={'spider': spider})
self._persist_stats(self._stats, spider)
def _persist_stats(self, stats, spider):
pass
上面是数据收集器的源码,可以看到在close_spider中会将self._stats打印出来,默认收集的信息如下。
结束时:
{'downloader/request_bytes': 20646,
'downloader/request_count': 47,
'downloader/request_method_count/POST': 47,
'downloader/response_bytes': 673679,
'downloader/response_count': 47,
'downloader/response_status_count/200': 47,
'finish_reason': 'shutdown',
'finish_time': datetime.datetime(2018, 7, 24, 6, 31, 1, 84791),
'item_scraped_count': 460,
'log_count/CRITICAL': 4,
'log_count/DEBUG': 510,
'log_count/ERROR': 1,
'log_count/INFO': 74,
'login_faild': False,
'request_depth_max': 46,
'response_received_count': 47,
'scheduler/dequeued': 47,
'scheduler/dequeued/memory': 47,
'scheduler/enqueued': 48,
'scheduler/enqueued/memory': 48,
'spider_exceptions/KeyError': 1,
'start_time': datetime.datetime(2018, 7, 24, 6, 12, 27, 74073)}
结束时会有finish_reason,finish_time两个值,在运行时没有。
数据收集器允许添加开发者收集自定义数据:
在spider中:
self.crawler.stats.set_value("login_faild", False)
在Middleware和Pipeline中:
spider.crawler.stats.set_value("login_faild", False)
进入正题如何远程获取收集器中的数据
第一种:保存后获取,在downloadMiddleware中将状态信息写入redis中,在读取:
import redis
import time
import requests
class StatCollectorMiddleware(object):
def __init__(self):
self.r = redis.Redis(host='localhost', port=6379, db=0)
self.time = lambda: time.strftime('%Y-%m-%d %H:%M:%S')
def process_request(self, request, spider):
stats = spider.crawler.stats.get_stats()
for key, value in stats.items():
value = {"value": [self.time(), key_value]}
self.insert2redis(key, value)
def insert2redis(self, key, value):
self.r.rpush(key, value)
第二种:使用Telnet Console获取,首先配置setting,允许外网访问,记得开启6023端口,
TELNETCONSOLE_HOST = '0.0.0.0'
TELNETCONSOLE_PORT = [6023, 6073]
默认配置
TELNETCONSOLE_HOST = '127.0.0.1'
TELNETCONSOLE_PORT = [6023, 6073]
然后使用
import telnetlib
tn = telnetlib.Telnet('192.168.2.89', port=6023, timeout=10)
tn.write('stats.get_stats()'+'\n')
tn.read_very_eager()
结果:
In [1]: import telnetlib
In [2]: tn = telnetlib.Telnet('192.168.2.89', port=6023, timeout=10)
In [3]: tn.write('stats.get_stats()'+'\n')
In [4]: stat = tn.read_very_eager()
In [5]: print stat
>>> stats.get_stats()
{'log_count/INFO': 45, 'start_time': datetime.datetime(2018, 7, 24, 6, 49, 26, 572021), 'log_count/DEBUG': 394, 'login_faild': False, 'sched uler/enqueued/memory': 37, 'scheduler/enqueued': 37, 'scheduler/dequeued/memory': 37, 'scheduler/dequeued': 37, 'downloader/request_count': 37, 'downloader/request_method_count/POST': 37, 'downloader/request_bytes': 16286, 'downloader/response_count': 37, 'downloader/response_sta tus_count/200': 37, 'downloader/response_bytes': 531739, 'response_received_count': 37, 'item_scraped_count': 354, 'request_depth_max': 35, 'log_count/ERROR': 1, 'spider_exceptions/KeyError': 1, 'log_count/CRITICAL': 4}
>>>
当有多个爬虫时可以将端口配置在spider中,避免冲突:
custom_settings = {
"TELNETCONSOLE_PORT": [6029, ]
}
这样就可以在远程获取状态信息了,虽然是在局域网测试,但是外网同样可以。