Scrapy CrawlSpider 后处理:计算平均值
假设我有一个爬虫程序,类似于这个例子:
从 scrapy.contrib.spiders 导入 CrawlSpider 和 Rule,从 scrapy.contrib.linkextractors.sgml 导入 SgmlLinkExtractor,从 scrapy.selector 导入 HtmlXPathSelector,从 scrapy.item 导入 Item
class MySpider(CrawlSpider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = ['http://www.example.com']
rules = (
# Extract links matching 'category.php' (but not matching 'subsection.php')
# and follow links from them (since no callback means follow=True by default).
Rule(SgmlLinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
# Extract links matching 'item.php' and parse them with the spider's method parse_item
Rule(SgmlLinkExtractor(allow=('item\.php', )), callback='parse_item'),
)
def parse_item(self, response):
self.log('Hi, this is an item page! %s' % response.url)
hxs = HtmlXPathSelector(response)
item = Item()
item['id'] = hxs.select('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
item['name'] = hxs.select('//td[@id="item_name"]/text()').extract()
item['description'] = hxs.select('//td[@id="item_description"]/text()').extract()
return item
假设我想从每个页面获取一些信息,比如所有页面的 ID 总和,或者所有解析页面中描述的平均字符数。我该怎么做呢?
另外,我还想知道如何获取某个特定类别的平均值?