[python爬虫]CrawlSpider爬虫入门学习

本文介绍了创建CrawlSpider爬虫的方法,包括使用LinkExtractor链接提取器自动爬取满足规则的URL,以及Rule规则类定义爬虫规则。还给出了糗事百科CrawlSpider案例,展示如何编写代码实现自动爬取数据,最后提供了demo地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建CrawlSpider爬虫

上篇博客中,写的创建爬虫的方式是通过 scrapy genspider [爬虫名字] [域名] 创建的。如果想要创建 CrawlSpider 爬虫,应该通过如下命令进行

scrapy genspider -t crawl [爬虫名字] [域名]
  • -t: 是选择模板生成代码,因为是要编写 CrawlSpider 爬虫所以选择 crawl 模板

输入 scrapy genspider -t crawl qsbk_two www.qiushibaike.com 后生成的python代码如下

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class QsbkTwoSpider(CrawlSpider):
    name = 'qsbk_two'
    allowed_domains = ['www.qiushibaike.com']
    start_urls = ['http://www.qiushibaike.com/']

    rules = (
        Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        i = {}
        #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
        #i['name'] = response.xpath('//div[@id="name"]').extract()
        #i['description'] = response.xpath('//div[@id="description"]').extract()
        return i

查看代码可以发现除了编写爬虫需要继承的 CrawlSpider 类外,还多了两个新的依赖 LinkExtractorRule

LinkExtractor链接提取器

使用LinkExtractors可以不用自己提取想要的url,然后发送请求。这些工作都可以交给LinkExtractors,他会在所有爬的页面中找到满足规则的url,实现自动的爬取。以下对LinkExtractors类做一个简单的介绍:

LinkExtractors 类的构造方法如下:

def __init__(self, 
                allow=(), 
                deny=(), 
                allow_domains=(), 
                deny_domains=(), 
                restrict_xpaths=(),
                tags=('a', 'area'), 
                attrs=('href',), 
                canonicalize=False,
                unique=True, 
                process_value=None, 
                deny_extensions=None, 
                restrict_css=(),
                strip=True):
                # 代码省略
                pass

主要参数讲解

参数名说明
allow允许的url。所有满足这个正则表达式的url都会被提取
deny禁止的url。所有满足这个正则表达式的url都不会被提取
allow_domains允许的域名。只有在这个里面指定的域名的url才会被提取
deny_domains禁止的域名。所有在这个里面指定的域名的url都不会被提取
restrict_xpaths严格的xpath。和allow共同过滤链接

Rule规则类

定义爬虫的规则类。以下对这个类做一个简单的介绍:

构造函数如下:

def __init__(self, 
                link_extractor, 
                callback=None, 
                cb_kwargs=None, 
                follow=None, 
                process_links=None, 
                process_request=identity):
    # 代码省略
    pass

主要参数讲解

参数名说明
link_extractor一个LinkExtractor对象,用于定义爬取规则
callback满足这个规则的url,应该要执行哪个回调函数。因为CrawlSpider使用了parse作为回调函数,因此不要覆盖parse作为回调函数自己的回调函数
follow指定根据该规则从response中提取的链接是否需要跟进
process_links从link_extractor中获取到链接后会传递给这个函数,用来过滤不需要爬取的链接

糗事百科CrawlSpider案例

依照上篇博客的代码在spiders包中新添加一个 CrawlSpider 爬虫类
代码如下

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from qsbk.items import QsbkItem
import time


class QsbkTwoSpider(CrawlSpider):
    name = 'qsbk_two'
    allowed_domains = ['www.qiushibaike.com']
    start_urls = ['https://www.qiushibaike.com/text/']

    link_extractor = LinkExtractor(allow='/text/page/\d+/')
    rules = (
        Rule(link_extractor=link_extractor, callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        outerbox = response.xpath("//div[@id='content-left']/div")
        items = []
        for box in outerbox:
            detail_url = str(box.xpath("a[1]/@href").get()).strip()
            author = str(box.xpath("div[@class='author clearfix']/a/h2/text()").get()).strip()
            content = str(box.xpath("a/div[@class='content']/span/text()").get()).strip()

            item = QsbkItem()
            item['detail_url'] = detail_url
            item['author'] = author
            item['content'] = content

            cmt_box = box.xpath("a[@class='indexGodCmt']")
            if len(cmt_box) > 0:
                cmt_name = str(cmt_box[0].xpath("div/span[@class='cmt-name']/text()").get()).strip()[0:-1]
                item['cmt_name'] = cmt_name
                cmt_content = str(cmt_box[0].xpath("div/div/text()").get()).strip()
                item['cmt_content'] = cmt_content
            items.append(item)
        return items

parse_item方法中的代码和之前的爬虫代码相差不大,只是多了爬取审评字段,这里直接看代码不在过多描述,主要说下 link_extractorrules

  • link_extractor: 经检查发现每页的链接是/text/page/[数字]/这种形式,所以我们可以通过编写一个简单的正则对链接进行过滤 /text/page/\d+/。链接如果前边没域名CrawlSpider会自动将当前网站的域名拼接上去。

  • rules: link_extractor参数传入了上边创建好的LinkExtractor对象,callback 参数指定了创建的 parse_item 为回调方法,follow 参数设置为 True 指定如果提取到链接则请求新的链接继续执行

然后修改 start.py 中的启动命令为 scrapy crawl qsbk_two 来启动新创建的这个爬虫,然后可以看到CrawlSpider会自动爬取每页的数据,以爬取过的链接会自动过滤不会进行重复请求

demo地址

https://gitee.com/fengzxia/python_crawler_learning/blob/master/scrapy/qiushibaike/qsbk/spiders/qsbk_two.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值