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

相关推荐
麦麦大数据7 分钟前
F004 新闻可视化系统爬虫更新数据+ flask + mysql架构
爬虫·mysql·flask·可视化·新闻
python-行者24 分钟前
akamai鼠标轨迹
爬虫·python·计算机外设·akamai
NEUMaple19 小时前
python爬虫(四)----requests
开发语言·爬虫·python
电商API_1800790524721 小时前
大规模调用淘宝商品详情 API 的分布式请求调度实践
服务器·数据库·分布式·爬虫
小白学大数据1 天前
1688商品数据抓取:Python爬虫+动态页面解析
爬虫·python·okhttp
forestsea1 天前
Nginx蜘蛛请求智能分流:精准识别爬虫并转发SEO渲染服务
运维·爬虫·nginx
华科云商xiao徐1 天前
突破Python性能墙:关键模块C++化的爬虫优化指南
c++·爬虫·python
guidovans1 天前
基于大语言模型的爬虫数据清洗与结构化
人工智能·爬虫·语言模型·自然语言处理
憨憨の大鸭鸭2 天前
python爬虫学习(2)
爬虫·学习
大数据魔法师2 天前
Python网络爬虫(二) - 解析静态网页
爬虫·python