Scrapy | 爬取笑话网来认识继承自Spider的crawlspider爬虫类

crawlspider

    • [1. 创建crawlspider爬虫](#1. 创建crawlspider爬虫)
    • [2. 实战-爬取笑话网笑话](#2. 实战-爬取笑话网笑话)

本篇内容旨在拓展视野和知识,了解crawlspider的使用即可,主要熟悉掌握spider类的使用

CrawlSpider 提供了一种更高级的方法来定义爬取规则,而无需编写大量的重复代码。它基于规则系统工作,其中每个规则由一个或多个链接提取器(LinkExtractor)和一个回调函数(callback)组成。规则定义了要提取的链接和如何处理这些链接的方法。

  1. 自动根据规则提取链接并且发送给引擎
  2. 回调函数是指定规则要调用的方法。当链接提取器提取到链接时,将会调用相应的回调函数来处理提取到的
  3. follow 参数:在规则中,可以设置 follow 参数来决定是否继续跟踪从链接提取器提取的链接。如果设置为 True,则会继续跟踪这些链接并提取数据;如果设置为 False,则不会跟踪这些链接。

1. 创建crawlspider爬虫

  • 命令
python 复制代码
spider genspider [-t crawl]  name  domains
  • 总步骤
python 复制代码
1. scrapy startproject  projectname
2. cd projectname
3. spider genspider -t crawl spidername  domains
4. scrapy crawl  spidername 

2. 实战-爬取笑话网笑话

网址:笑话网

python 复制代码
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from jianshu.items import JianshuItem
#cralspider经常应用于数据在一个页面上进行采集的情况,如果数据在多个页面上采集,这个时候通常使用spider

class JiansuSpider(CrawlSpider):
    name = 'jiansu'
    allowed_domains = ['biedoul.com']
    start_urls = ['https://www.biedoul.com/']
    # LinkExtractor)用于设置链接提取规则,一般使用allow参数,接收正则表达式
    # foLLOW参数决定是否在链接提取器提取的链接对应的响应中继续应用链接提取器提取链接
    # #使用RuLe类生成链接提取规则对象

    rules = (
        Rule(LinkExtractor(allow=r'/article/[0-9]+$'), callback='parse_item',follow=False),
		# 翻页请求   无需callback参数
        Rule(LinkExtractor(allow=r'/index/[0-9]+/$'),follow=True),
    )
    
    #在crawlspider中不能冲写parse方法
    def parse_item(self, response):
        item = JianshuItem()

        item['name'] = response.xpath('/html/body/div[3]/div/div[1]/div[1]/div[1]/div[1]/h1/text()').get()
        item['description'] = response.xpath('/html/body/div[3]/div/div[1]/div[1]/div[1]/div[2]/div/text()').get()

        yield item
  • 结果
  • 强调
python 复制代码
    rules = (
        Rule(LinkExtractor(allow=r'/article/[0-9]+$'), callback='parse_item',follow=False)
        )

callback='parse_item' 不同于spider爬虫类 callback参数 不是self.parse_item

相关推荐
猫猫村晨总2 小时前
网络爬虫学习之httpx的使用
爬虫·python·httpx
大神薯条老师13 小时前
Python零基础入门到高手8.4节: 元组与列表的区别
开发语言·爬虫·python·深度学习·机器学习·数据分析
小白学大数据13 小时前
Python爬虫如何应对网站的反爬加密策略?
开发语言·爬虫·python
北漂老男孩15 小时前
ChromeDriver 技术生态与应用场景深度解析
java·爬虫·python·自动化
咕噜咕噜啦啦19 小时前
Python爬虫入门
开发语言·爬虫·python
小白学大数据1 天前
Python+Selenium爬虫:豆瓣登录反反爬策略解析
分布式·爬虫·python·selenium
攻城狮7号1 天前
Python爬虫第21节- 基础图形验证码识别实战
开发语言·爬虫·python·图形验证码识别
顾一大人2 天前
dp自动化登陆之hCaptcha 验证码
爬虫·python·自动化
whoarethenext2 天前
c/c++爬虫总结
c语言·c++·爬虫
Dreams°1232 天前
【Python爬虫 !!!!!!政府招投标数据爬虫项目--医疗实例项目文档(提供源码!!!)!!!学会Python爬虫轻松赚外快】
分布式·爬虫·python·mysql·scikit-learn