Scrapy 提供了方便的收集數(shù)據(jù)的機(jī)制。數(shù)據(jù)以 key/value 方式存儲(chǔ),值大多是計(jì)數(shù)值。 該機(jī)制叫做數(shù)據(jù)收集器(Stats Collector),可以通過 Crawler API 的屬性 stats
來使用。在下面的章節(jié)常見數(shù)據(jù)收集器使用方法將給出例子來說明。
無論數(shù)據(jù)收集(stats collection)開啟或者關(guān)閉,數(shù)據(jù)收集器永遠(yuǎn)都是可用的。因此您可以 import 進(jìn)自己的模塊并使用其 API(增加值或者設(shè)置新的狀態(tài)鍵(stat keys))。該做法是為了簡化數(shù)據(jù)收集的方法: 您不應(yīng)該使用超過一行代碼來收集您的 spider,Scrpay 擴(kuò)展或任何您使用數(shù)據(jù)收集器代碼里頭的狀態(tài)。
數(shù)據(jù)收集器的另一個(gè)特性是(在啟用狀態(tài)下)很高效,(在關(guān)閉情況下)非常高效(幾乎察覺不到)。
數(shù)據(jù)收集器對每個(gè) spider 保持一個(gè)狀態(tài)表。當(dāng) spider 啟動(dòng)時(shí),該表自動(dòng)打開,當(dāng) spider 關(guān)閉時(shí),自動(dòng)關(guān)閉。
通過 stats 屬性來使用數(shù)據(jù)收集器。 下面是在擴(kuò)展中使用狀態(tài)的例子:
class ExtensionThatAccessStats(object):
def __init__(self, stats):
self.stats = stats
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.stats)
設(shè)置數(shù)據(jù):
stats.set_value('hostname', socket.gethostname())
增加數(shù)據(jù)值:
stats.inc_value('pages_crawled')
當(dāng)新的值比原來的值大時(shí)設(shè)置數(shù)據(jù):
stats.max_value('max_items_scraped', value)
當(dāng)新的值比原來的值小時(shí)設(shè)置數(shù)據(jù):
stats.min_value('min_free_memory_percent', value)
獲取數(shù)據(jù):
>>> stats.get_value('pages_crawled')
8
獲取所有數(shù)據(jù):
>>> stats.get_stats()
{'pages_crawled': 1238, 'start_time': datetime.datetime(2009, 7, 14, 21, 47, 28, 977139)}
除了基本的 StatsCollector
,Scrapy 也提供了基于 StatsCollector
的數(shù)據(jù)收集器。 您可以通過 STATS_CLASS
設(shè)置來選擇。默認(rèn)使用的是 MemoryStatsCollector
。
一個(gè)簡單的數(shù)據(jù)收集器。其在 spider 運(yùn)行完畢后將其數(shù)據(jù)保存在內(nèi)存中。數(shù)據(jù)可以通過 spider_stats 屬性訪問。該屬性是一個(gè)以 spider 名字為鍵(key)的字典。
這是 Scrapy 的默認(rèn)選擇。
保存了每個(gè) spider 最近一次爬取的狀態(tài)的字典(dict)。該字典以 spider 名字為鍵,值也是字典。
該數(shù)據(jù)收集器并不做任何事情但非常高效。您可以通過設(shè)置 STATS_CLASS 啟用這個(gè)收集器,來關(guān)閉數(shù)據(jù)收集,提高效率。 不過,數(shù)據(jù)收集的性能負(fù)擔(dān)相較于 Scrapy 其他的處理(例如分析頁面)來說是非常小的。