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

相关推荐
电商API_180079052478 小时前
构建高效可靠的电商 API:设计原则与实践指南
运维·服务器·爬虫·数据挖掘·网络爬虫
waterHBO11 小时前
python 爬虫工具 mitmproxy, 几问几答,记录一下
开发语言·爬虫·python
武子康1 天前
AI炼丹日志-28 - Audiblez 将你的电子书epub转换为音频mp3 做有声书
人工智能·爬虫·gpt·算法·机器学习·ai·音视频
AIGC_北苏1 天前
DrissionPage爬虫包实战分享
爬虫·python·drissionpage
华科云商xiao徐1 天前
增量式网络爬虫通用模板
爬虫
仟濹1 天前
「数据分析 - Pandas 函数」【数据分析全栈攻略:爬虫+处理+可视化+报告】
爬虫·数据分析·pandas
爬虫程序猿1 天前
利用 Python 爬虫获取淘宝商品详情
开发语言·爬虫·python
FAQEW2 天前
爬虫的几种方式(使用什么技术来进行一个爬取数据)
爬虫·python
cooldream20092 天前
利用 Scrapy 构建高效网页爬虫:框架解析与实战流程
爬虫·scrapy·架构
Dxy12393102162 天前
DrissionPage调试工具:网页自动化与数据采集的革新利器
爬虫·python·drissionpage