python爬虫scrapy基于CrawlSpider类的全站数据爬取示例解析


Posted in Python onFebruary 20, 2021

一、CrawlSpider类介绍

1.1 引入

使用scrapy框架进行全站数据爬取可以基于Spider类,也可以使用接下来用到的CrawlSpider类。基于Spider类的全站数据爬取之前举过栗子,感兴趣的可以康康

1.2 介绍和使用

1.2.1 介绍

CrawlSpider是Spider的一个子类,因此CrawlSpider除了继承Spider的特性和功能外,还有自己特有的功能,主要用到的是 LinkExtractor()rules = (Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),)

LinkExtractor()链接提取器
LinkExtractor()接受response对象,并根据allow对应的正则表达式提取响应对象中的链接

link = LinkExtractor(
# Items只能是一个正则表达式,会提取当前页面中满足该"正则表达式"的url	
  allow=r'Items/'
)

rules = (Rule(link, callback='parse_item', follow=True),)规则解析器
按照指定规则从链接提取器中提取到的链接中解析网页数据
link:是一个LinkExtractor()对象,指定链接提取器
callback:回调函数,指定规则解析器(解析方法)解析数据
follow:是否将链接提取器继续作用到链接提取器提取出的链接网页

import scrapy
# 导入相关的包
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class TextSpider(CrawlSpider):
 name = 'text'
 allowed_domains = ['www.xxx.com']
 start_urls = ['http://www.xxx.com/']

# 链接提取器,从接受到的response对象中,根据item正则表达式提取页面中的链接
	link = LinkExtractor(allow=r'Items/')
	link2 = LinkExtractor(allow=r'Items/')
# 规则解析器,根据callback将链接提取器提取到的链接进行数据解析
# follow为true,则表示将链接提取器继续作用到链接提取器所提取到的链接页面中
# 故:在我们提取多页数据时,若第一页对应的网页中包含了第2,3,4,5页的链接,
# 当跳转到第5页时,第5页又包含了第6,7,8,9页的链接,
# 令follow=True,就可以持续作用,从而提取到所有页面的链接
 rules = (Rule(link, callback='parse_item', follow=True),
 		Rule(link2,callback='parse_content',follow=False))
 # 链接提取器link使用parse_item解析数据
	def parse_item(self, response):
 item = {}
 
 yield item
 # 链接提取器link2使用parse_content解析数据
	def parse_content(self, response):
		item = {}
		
		yield item

1.2.2 使用

创建爬虫文件:除了创建爬虫文件不同外,创建项目和运行爬虫使用的命令和基于Spider类使用的命令相同

scrapy genspider crawl -t spiderName www.xxx.com

二、案例:古诗文网全站数据爬取

爬取古诗文网首页古诗的标题,以及每一首诗详情页古诗的标题和内容。
最后将从详情页提取到的古诗标题和内容进行持久化存储

2.1 爬虫文件

import scrapy
from scrapy.linkextractors import LinkExtractor

from scrapy.spiders import CrawlSpider, Rule
from gushiPro.items import GushiproItem,ContentItem

class GushiSpider(CrawlSpider):
 name = 'gushi'
 #allowed_domains = ['www.xxx.com']
 start_urls = ['https://www.gushiwen.org/']

 # 链接提取器:只能使用正则表达式,提取当前页面的满足allow条件的链接
 link = LinkExtractor(allow=r'/default_\d+\.aspx')

 # 链接提取器,提取所有标题对应的详情页url
 content_link = LinkExtractor(allow=r'cn/shiwenv_\w+\.aspx')
 rules = (
 # 规则解析器,需要解析所有的页面,所有follow=True
 Rule(link, callback='parse_item', follow=True),

 # 不需要写follow,因为我们只需要解析详情页中的数据,而不是详情页中的url
 Rule(content_link, callback='content_item'),
 )

 # 解析当前页面的标题
 def parse_item(self, response):
 p_list = response.xpath('//div[@class="sons"]/div[1]/p[1]')

 for p in p_list:
 title = p.xpath('./a//text()').extract_first()
 item = GushiproItem()
 item['title'] = title
 yield item
 
 # 解析详情页面的标题和内容
 def content_item(self,response):
 # //div[@id="sonsyuanwen"]/div[@class="cont"]/div[@class="contson"]
 # 解析详情页面的内容
 content = response.xpath('//div[@id="sonsyuanwen"]/div[@class="cont"]/div[@class="contson"]//text()').extract()
 content = "".join(content)
 # # 解析详情页面的标题
 title = response.xpath('//div[@id="sonsyuanwen"]/div[@class="cont"]/h1/text()').extract_first()
 # print("title:"+title+"\ncontent:"+content)
 item = ContentItem()
 item["content"] = content
 item["title"] = title
 # 将itme对象传给管道
 yield item

2.2 item文件

import scrapy

# 不同的item类是独立的,他们可以创建不同的item对象
class GushiproItem(scrapy.Item):
 # define the fields for your item here like:
 # name = scrapy.Field()
 title = scrapy.Field()

class ContentItem(scrapy.Item):
 title = scrapy.Field()
 content = scrapy.Field()

2.3 管道文件

from itemadapter import ItemAdapter

class GushiproPipeline:
 def __init__(self):
 self.fp = None

 def open_spider(self,spider):
 self.fp = open("gushi.txt",'w',encoding='utf-8')
 print("开始爬虫")

 def process_item(self, item, spider):
 # 从详情页获取标题和内容,所以需要判断爬虫文件中传来的item是什么类的item
 # item.__class__.__name__判断属于什么类型的item
 if item.__class__.__name__ == "ContentItem":
 content = "《"+item['title']+"》",item['content']
 content = "".join(content) 
 print(content)
 self.fp.write(content)
 return item

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

2.4 配置文件

python爬虫scrapy基于CrawlSpider类的全站数据爬取示例解析

2.5 输出结果

python爬虫scrapy基于CrawlSpider类的全站数据爬取示例解析

到此这篇关于python爬虫scrapy基于CrawlSpider类的全站数据爬取示例解析的文章就介绍到这了,更多相关python爬虫scrapy数据爬取内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python的设计模式编程入门指南
Apr 02 Python
scrapy自定义pipeline类实现将采集数据保存到mongodb的方法
Apr 16 Python
在Python中使用元类的教程
Apr 28 Python
Python实现将目录中TXT合并成一个大TXT文件的方法
Jul 15 Python
Python实现简易Web爬虫详解
Jan 03 Python
Python实现的本地文件搜索功能示例【测试可用】
May 30 Python
Anaconda 离线安装 python 包的操作方法
Jun 11 Python
Python 比较文本相似性的方法(difflib,Levenshtein)
Oct 15 Python
Python利用heapq实现一个优先级队列的方法
Feb 03 Python
django框架model orM使用字典作为参数,保存数据的方法分析
Jun 24 Python
HTML的form表单和django的form表单
Jul 25 Python
Pycharm插件(Grep Console)自定义规则输出颜色日志的方法
May 27 Python
TensorFlow的环境配置与安装方法
Feb 20 #Python
python爬虫爬取某网站视频的示例代码
Feb 20 #Python
python爬虫线程池案例详解(梨视频短视频爬取)
Feb 20 #Python
python爬虫scrapy框架的梨视频案例解析
Feb 20 #Python
Keras保存模型并载入模型继续训练的实现
Feb 20 #Python
TensorFlow2.0使用keras训练模型的实现
Feb 20 #Python
tensorflow2.0教程之Keras快速入门
Feb 20 #Python
You might like
PHP.MVC的模板标签系统(二)
2006/09/05 PHP
php自定义函数之递归删除文件及目录
2010/08/08 PHP
php页面防重复提交方法总结
2013/11/25 PHP
php将access数据库转换到mysql数据库的方法
2014/12/24 PHP
PHP动态生成指定大小随机图片的方法
2016/03/25 PHP
JQuery学习笔记 nt-child的使用
2011/01/17 Javascript
javascript获取元素离文档各边距离的方法
2015/02/13 Javascript
初步了解javascript面向对象
2015/11/09 Javascript
JQuery EasyUI的使用
2016/02/24 Javascript
省市选择的简单实现(基于zepto.js)
2016/06/21 Javascript
JS+CSS3实现超炫的散列画廊特效
2016/07/16 Javascript
Nodejs实现短信验证码功能
2017/02/09 NodeJs
jQuery操作之效果详解
2017/05/19 jQuery
JavaScript实现构造json数组的方法分析
2018/08/17 Javascript
js图片无缝滚动插件使用详解
2020/05/26 Javascript
Vue作用域插槽实现方法及作用详解
2020/07/08 Javascript
vue监听键盘事件的相关总结
2021/01/29 Vue.js
python测试驱动开发实例
2014/10/08 Python
Python实现遍历windows所有窗口并输出窗口标题的方法
2015/03/13 Python
python编写Logistic逻辑回归
2020/12/30 Python
调整Jupyter notebook的启动目录操作
2020/04/10 Python
Python 必须了解的5种高级特征
2020/09/10 Python
super()与this()的区别
2016/01/17 面试题
会计实习自我鉴定
2013/12/04 职场文书
合作经营协议书范本
2014/04/17 职场文书
中学生打架检讨书
2014/10/13 职场文书
公司离职证明标准格式
2014/11/18 职场文书
2014年派出所工作总结
2014/11/21 职场文书
2014年世界艾滋病日演讲稿
2014/11/28 职场文书
神农溪导游词
2015/02/11 职场文书
张丽莉观后感
2015/06/16 职场文书
小数乘法教学反思
2016/02/22 职场文书
python中的class_static的@classmethod的巧妙用法
2021/06/22 Python
JavaScript数组reduce()方法的语法与实例解析
2021/07/07 Javascript
Mysql如何实现不存在则插入,存在则更新
2022/03/25 MySQL
SQL使用复合索引实现数据库查询的优化
2022/05/25 SQL Server