0

假设我有一个类似于这个例子的爬虫: from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import 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 总和,或者所有已解析页面的描述中的平均字符数。我该怎么做?

另外,我怎样才能获得特定类别的平均值?

4

1 回答 1

3

您可以使用 Scrapy 的统计数据收集器来构建此类信息或收集必要的数据以在您进行时这样做。对于每个类别的统计信息,您可以使用每个类别的统计信息键。

要快速转储爬网期间收集的所有统计信息,您可以添加STATS_DUMP = True到您的settings.py.

Redis(通过redis-py)也是统计数据收集的绝佳选择。

于 2011-03-27T09:11:01.367 回答