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

相关推荐
喵手9 小时前
Python爬虫实战:HTTP缓存系统深度实战 — ETag、Last-Modified与requests-cache完全指南(附SQLite持久化存储)!
爬虫·python·爬虫实战·http缓存·etag·零基础python爬虫教学·requests-cache
喵手9 小时前
Python爬虫实战:容器化与定时调度实战 - Docker + Cron + 日志轮转 + 失败重试完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·容器化·零基础python爬虫教学·csv导出·定时调度
喵手11 小时前
Python爬虫实战:全站 Sitemap 自动发现 - 解析 sitemap.xml → 自动生成抓取队列的工业级实现!
爬虫·python·爬虫实战·零基础python爬虫教学·sitemap·解析sitemap.xml·自动生成抓取队列实现
iFeng的小屋12 小时前
【2026年新版】Python根据小红书关键词爬取所有笔记数据
笔记·爬虫·python
Love Song残响13 小时前
揭秘Libvio爬虫:动态接口与逆向实战
爬虫
喵手15 小时前
Python爬虫实战:构建招聘会数据采集系统 - requests+lxml 实战企业名单爬取与智能分析!
爬虫·python·爬虫实战·requests·lxml·零基础python爬虫教学·招聘会数据采集
iFeng的小屋15 小时前
【2026最新当当网爬虫分享】用Python爬取千本日本相关图书,自动分析价格分布!
开发语言·爬虫·python
数研小生16 小时前
关键词搜索京东列表API技术对接指南
大数据·数据库·爬虫
喵手16 小时前
Python爬虫实战:网页截图归档完全指南 - 构建生产级页面存证与历史回溯系统!
爬虫·python·爬虫实战·零基础python爬虫教学·网页截图归档·历史回溯·生产级方案
Blurpath住宅代理17 小时前
动态代理的五大优点:提升爬虫效率与安全性
网络·爬虫·动态ip·住宅ip·住宅代理