Scrapy 爬虫模板--CrawlSpider

时间:2022-07-24
本文章向大家介绍Scrapy 爬虫模板--CrawlSpider,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

从这篇文章开始,我将利用三篇文章分别讲解 Scrapy 爬虫模板。 Scrapy 爬虫模板包含四个模板:

  1. Basic :最基本的模板,这里我们不会讲解;
  2. CrawlSpider
  3. XMLFeedSpider
  4. CSVFEEDSpider

这篇文章我先来讲解一下 CrawlSpider 模板。

零、讲解

CrawlSpider 是常用的 Spider ,通过定制规则来跟进链接。对于大部分网站我们可以通过修改规则来完成爬取任务。 CrawlSpider 常用属性是 rules* ,它是一个或多个 Rule 对象以 tuple 的形式展现。其中每个 Rule 对象定义了爬取目标网站的行为。

Tip:如果有多个 Rule 对象命中同一个链接,那么只有第一个 Rule 对象生效。

我们来看一下 Role 的语法:

Rule(link_extractor [,callback = None] [,cb_kwargs = None] [,follow = None] [,process_links = None] [,process_request = None])

参数解析:

  • link_extractor:Link Extrator 对象,是一个正则表达式。主要定义了从网页中提取哪些元素作为继续跟进的链接;
  • callback:回调函数,也可以是回调函数的字符串名。接收 Response 作为参数,返回包含 Item 或者 Request 对象列表;
  • cb_kwargs:字典类型的对象,传递给回调函数的参数;
  • follow:是否根据这个 Rule 的 link_extractor 从 Response 中提取链接;
  • process_links:回调函数,也可以是回调函数的字符串名。从link_extractor中获取到链接列表时将会调用该函数。该方法主要用来过滤;
  • process_request:回调函数,也可以是回调函数的字符串名。用来过滤 Request ,该规则提取到每个 Request 时都会调用该函数。

一、案例

这个案例我们爬取的是名人名言网站,我们需要做的是提取名言内容、作者姓名和标签,然后通过作者链接进入到作者介绍的页面,最后我们爬取的作者的详细信息。

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class Quotes(CrawlSpider):
    name = "quotes"
    allow_domain = ['quotes.toscrape.com']
    start_urls = ['http://quotes.toscrape.com']

    rules = (
        Rule(LinkExtractor(allow='/page/d+'), callback='parse_quotes', follow=True),
        Rule(LinkExtractor(allow='/author/w+_'), callback='parse_author')
    )

    def parse_quotes(self, response):
        for quote in response.css('.quote'):
            yield {
                'content': quote.css('.text::text').extract_first(),
                'author': quote.css('.author::text').extract_first(),
                'tags': quote.css('.tag::text').extract()
            }

    def parse_author(self, response):
        name = response.css('.author-title::text').extract_first()
        author_born_date = response.css('.author_born_date::text').extract_first()
        author_description = response.css('.author_description::text').extract_first()
        return ({
            'name': name,
            'author_born_date': author_born_date,
            'author_description': author_description
        })
        import scrapy
        from scrapy.spiders import CrawlSpider, Rule
        from scrapy.linkextractors import LinkExtractor


        class Quotes(CrawlSpider):
            name = "quotes"
            allow_domain = ['quotes.toscrape.com']
            start_urls = ['http://quotes.toscrape.com']

            rules = (
                Rule(LinkExtractor(allow='/page/d+'), callback='parse_quotes', follow=True),
                Rule(LinkExtractor(allow='/author/w+_'), callback='parse_author')
            )

            def parse_quotes(self, response):
                for quote in response.css('.quote'):
                    yield {
                        'content': quote.css('.text::text').extract_first(),
                        'author': quote.css('.author::text').extract_first(),
                        'tags': quote.css('.tag::text').extract()
                    }

            def parse_author(self, response):
                name = response.css('.author-title::text').extract_first()
                author_born_date = response.css('.author_born_date::text').extract_first()
                author_description = response.css('.author_description::text').extract_first()
                return ({
                    'name': name,
                    'author_born_date': author_born_date,
                    'author_description': author_description
                })

上述代码中 Rule(LinkExtractor(allow='/page/d+'), callback='parse_quotes', follow=True),代码段定义了爬取所有名人名言页的规则,即只要符合 /page/d+的所有链接就被视为名人名言页,然后我们调用 parse_quotes 方法提取相关数据。 在 Rule(LinkExtractor(allow='/author/w+_'), callback='parse_author')代码段中我们定义了爬取作者信息页的规则,即只要符合 /author/w+_的所有链接就被视为作者信息页,之后我们调用 parse_author 方法提取相关数据。 )代码段中我们定义了爬取作者信息页的规则,即只要符合/author/w+_```的所有链接就被视为作者信息页,之后我们调用 parse_author 方法提取相关数据。