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

相关推荐
Auroral1563 小时前
【Python爬虫详解】第五篇:使用正则表达式提取网页数据
爬虫
一个天蝎座 白勺 程序猿6 小时前
Python爬虫(4)CSS核心机制:全面解析选择器分类、用法与实战应用
css·爬虫·python
丰锋ff13 小时前
爬虫学习总结
爬虫
西柚小萌新16 小时前
【Python爬虫基础篇】--4.Selenium入门详细教程
爬虫·python·selenium
橘猫云计算机设计17 小时前
springboot基于hadoop的酷狗音乐爬虫大数据分析可视化系统(源码+lw+部署文档+讲解),源码可白嫖!
数据库·hadoop·spring boot·爬虫·python·数据分析·毕业设计
??? Meggie21 小时前
Selenium 怎么加入代理IP,以及怎么检测爬虫运行的时候,是否用了代理IP?
爬虫·tcp/ip·selenium
用户199701080181 天前
深入解析淘宝商品详情 API 接口:功能、使用与实践指南
大数据·爬虫·数据挖掘
西柚小萌新1 天前
【Python爬虫实战篇】--Selenium爬取Mysteel数据
开发语言·爬虫·python
Auroral1561 天前
【Python爬虫详解】第四篇:使用解析库提取网页数据——XPath
爬虫
Auroral1561 天前
【Python爬虫详解】第四篇:使用解析库提取网页数据——PyQuery
爬虫