Scrapy CrawlSpider 后处理:计算平均值

0 投票
1 回答
1804 浏览
提问于 2025-04-16 14:30

假设我有一个爬虫程序,类似于这个例子:

从 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 总和,或者所有解析页面中描述的平均字符数。我该怎么做呢?

另外,我还想知道如何获取某个特定类别的平均值?

1 个回答

3

你可以使用Scrapy的统计收集器来建立这类信息,或者在抓取过程中收集所需的数据。对于每个类别的统计信息,你可以使用每个类别的统计键。

如果你想快速查看在抓取过程中收集的所有统计数据,可以在你的settings.py文件中添加STATS_DUMP = True

Redis(通过redis-py)也是一个很好的统计数据收集选项。

撰写回答