[英]How to collect stats from within scrapy spider callback?
如何从蜘蛛回调中收集统计信息?
例子
class MySpider(Spider):
name = "myspider"
start_urls = ["http://example.com"]
def parse(self, response):
stats.set_value('foo', 'bar')
不确定要import
什么或如何提供一般的stats
信息。
从 scrapy 文档中查看统计信息页面。 文档说明了 Stats Collector,但可能需要将from scrapy.stats import stats
添加到您的蜘蛛代码中才能使用它。
编辑:冒着吹我自己的小号的风险,如果你在一个具体的例子之后,我发布了一个关于如何收集失败网址的答案。
EDIT2:经过大量谷歌搜索,显然不需要进口。 只需使用self.crawler.stats.set_value()
!
使用scrapy 0.24 - stats我通过以下方式使用它:
class TopSearchesSpider(CrawlSpider):
name = "topSearches"
allowed_domains = ["...domain..."]
start_urls = (
'http://...domain...',
)
def __init__(self, stats):
super(TopSearchesSpider, self).__init__()
self.stats = stats
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.stats)
def parse_start_url(self, response):
sel = Selector(response);
url = response.url;
self.stats.inc_value('pages_crawled')
...
super方法是调用 CrawlSpider 构造函数来执行自己的代码。
在你的蜘蛛类中添加这个
def my_parse(self, response):
print self.crawler.stats.get_stats()
如果你想在其他地方使用,你可以:
spider.crawler.stats.get_stats()
如果你想在作为 python 对象爬行后获取scrapy stats。 这可能会有所帮助 -
def spider_results(spider): results = [] stats = [] def crawler_results(signal, sender, item, response, spider): results.append(item) def crawler_stats(*args, **kwargs): stats.append(kwargs['sender'].stats.get_stats()) dispatcher.connect(crawler_results, signal=signals.item_scraped) dispatcher.connect(crawler_stats, signal=signals.spider_closed) process = CrawlerProcess() process.crawl(spider) # put our own spider class here process.start() # the script will block here until the crawling is finished return results, stats
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.