Python爬虫Scrapy框架CrawlSpider原理及使用案例

作者:迎风而来 时间:2023-12-23 07:41:55 

提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法?

方法一:基于Scrapy框架中的Spider的递归爬去进行实现的(Request模块回调)

方法二:基于CrawlSpider的自动爬去进行实现(更加简洁和高效)

一、简单介绍CrawlSpider

CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能。其中最显著的功能就是”LinkExtractors链接提取器“。Spider是所有爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适。

二、使用

1.创建scrapy工程(cmd切换到要创建项目的文件夹下执行):scrapy startproject projectName (如:scrapy startproject crawlPro)

2.创建爬虫文件(cmd切换到创建的项目下执行):scrapy genspider -t crawl spiderName www.xxx.com (如:scrapy genspider -t crawl crawlDemo www.qiushibaike.com)

--此指令对比以前的指令多了 "-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的,而不再是Spider这个基类。

3.启动爬虫文件(cmd基于步骤二的路径执行):scrapy crawl crawlDemo (启动的一定是name对应的值,如果爬虫文件与name的值不一致,任然以name的值进行启动)

观察生成的爬虫文件

crawlDemo.py


# -*- coding: utf-8 -*-
import scrapy
# 导入CrawlSpider相关模块
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

# 表示该爬虫程序是基于CrawlSpider类的
class CrawldemoSpider(CrawlSpider):
 name = 'crawlDemo'  #爬虫文件名称
 #allowed_domains = ['www.qiushibaike.com']
 start_urls = ['http://www.qiushibaike.com/']

#连接提取器:会去起始url响应回来的页面中提取指定的url
 link = LinkExtractor(allow=r'/8hr/page/\d+')
 #rules元组中存放的是不同的规则解析器(封装好了某种解析规则)
 rules = (
   #规则解析器:可以将连接提取器提取到的所有连接表示的页面进行指定规则(回调函数)的解析
   Rule(link, callback='parse_item', follow=True),
 )
 # 解析方法
 def parse_item(self, response):
   #print(response.url)
   divs = response.xpath('//div[@id="content-left"]/div')
   for div in divs:
     author = div.xpath('./div[@class="author clearfix"]/a[2]/h2/text()').extract_first()
     print(author)

CrawlSpider类和Spider类的最大不同是CrawlSpider多了一个rules属性,其作用是定义”提取动作“。在rules中可以包含一个或多个Rule对象,在Rule对象中包含了LinkExtractor对象。

三、生成的爬虫文件参数介绍

3.1 LinkExtractor:顾名思义,链接提取器。

LinkExtractor(

allow=r'Items/',# 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。

deny=xxx, # 满足正则表达式的则不会被提取。

restrict_xpaths=xxx, # 满足xpath表达式的值会被提取

restrict_css=xxx, # 满足css表达式的值会被提取

deny_domains=xxx, # 不会被提取的链接的domains。

)

- 作用:提取response中符合规则的链接。

3.2 Rule : 规则解析器。根据链接提取器中提取到的链接,根据指定规则提取解析器链接网页中的内容。

Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True)

- 参数介绍:

参数1:指定链接提取器

参数2:指定规则解析器解析数据的规则(回调函数)

参数3:是否将链接提取器继续作用到链接提取器提取出的链接网页中。当callback为None,参数3的默认值为true。

3.3 rules=( ):指定不同规则解析器。一个Rule对象表示一种提取规则。

3.4 CrawlSpider整体爬取流程:

a)爬虫文件首先根据起始url,获取该url的网页内容

b)链接提取器会根据指定提取规则将步骤a中网页内容中的链接进行提取

c)规则解析器会根据指定解析规则将链接提取器中提取到的链接中的网页内容根据指定的规则进行解析

d)将解析数据封装到item中,然后提交给管道进行持久化存储

四、基于CrawlSpider示例

创建爬虫项目和启动爬虫项目以及settings中配置自行完成,在这里不在追赘述

4.1爬虫文件


# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from qiubaiBycrawl.items import QiubaibycrawlItem
import re
class QiubaitestSpider(CrawlSpider):
 name = 'qiubaiTest'
 #起始url
 start_urls = ['http://www.qiushibaike.com/']

#定义链接提取器,且指定其提取规则
 page_link = LinkExtractor(allow=r'/8hr/page/\d+/')

rules = (
   #定义规则解析器,且指定解析规则通过callback回调函数
   Rule(page_link, callback='parse_item', follow=True),
 )

#自定义规则解析器的解析规则函数
 def parse_item(self, response):
   div_list = response.xpath('//div[@id="content-left"]/div')

for div in div_list:
     #定义item
     item = QiubaibycrawlItem()
     #根据xpath表达式提取糗百中段子的作者
     item['author'] = div.xpath('./div/a[2]/h2/text()').extract_first().strip('\n')
     #根据xpath表达式提取糗百中段子的内容
     item['content'] = div.xpath('.//div[@class="content"]/span/text()').extract_first().strip('\n')

yield item #将item提交至管道

4.2items文件


# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class QiubaibycrawlItem(scrapy.Item):
 # define the fields for your item here like:
 # name = scrapy.Field()
 author = scrapy.Field() #作者
 content = scrapy.Field() #内容

4.3管道文件


# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

class QiubaibycrawlPipeline(object):

def __init__(self):
   self.fp = None

def open_spider(self,spider):
   print('开始爬虫')
   self.fp = open('./data.txt','w')

def process_item(self, item, spider):
   #将爬虫文件提交的item写入文件进行持久化存储
   self.fp.write(item['author']+':'+item['content']+'\n')
   return item

def close_spider(self,spider):
   print('结束爬虫')
   self.fp.close()

来源:https://www.cnblogs.com/sui776265233/p/9724147.html

标签:Python,爬虫,Scrapy,框架,CrawlSpider
0
投稿

猜你喜欢

  • 使用Python从有道词典网页获取单词翻译

    2022-12-10 21:18:03
  • Javascript中的函数声明与函数表达式(奇技淫巧)

    2024-04-23 09:08:43
  • Python 异步等待任务集合

    2022-08-14 17:23:22
  • Pycharm 如何一键加引号的方法步骤

    2022-09-11 19:19:34
  • php mysql获取表字段名称和字段信息的三种方法

    2023-11-18 22:47:26
  • Nodejs 和Session 原理及实战技巧小结

    2024-05-13 10:06:08
  • Python基于mysql实现学生管理系统

    2024-01-24 05:57:47
  • Python为何不能用可变对象作为默认参数的值

    2022-11-30 13:42:04
  • SQL 尚未定义空闲 CPU 条件 - OnIdle 作业计划将不起任何作用

    2024-01-18 18:22:58
  • Mysql分库分表之后主键处理的几种方法

    2024-01-20 21:00:09
  • 47个惊人的CSS3动画演示

    2010-02-07 12:32:00
  • 详解PyTorch中Tensor的高阶操作

    2021-11-24 12:08:00
  • Django框架配置mysql数据库实现过程

    2024-01-20 00:35:23
  • Python+OpenCV解决彩色图亮度不均衡问题

    2023-02-08 23:14:53
  • JS中getElementsByClassName与classList兼容性问题解决方案分析

    2023-08-25 05:39:06
  • python中print()函数的“,”与java中System.out.print()函数中的“+”功能详解

    2021-12-18 10:27:02
  • python并发爬虫实用工具tomorrow实用解析

    2023-03-18 02:29:07
  • Python库安装速度过慢解决方案

    2023-09-14 14:57:30
  • ASP+MSSQL2000 数据库被批量注入后的解决方法第1/2页

    2011-04-06 10:50:00
  • Python之京东商品秒杀的实现示例

    2023-01-31 05:49:07
  • asp之家 网络编程 m.aspxhome.com