scrapy各种持久化存储的奇淫技巧
理论
磁盘文件:
基于终端指令
1)保证parse方法返回一个可迭代类型的对象(存储解析到的页面内容)
2)使用终端指令完成数据存储到指定磁盘文件中的操作,如:scrapy crawl 爬虫文件名称 -o 磁盘文件.后缀 --nolog
基于管道
items.py:存储解析到的页面数据
pipelines.py:处理持久化存储的相关操作
代码实现流程:
1)将解析到的页面数据存储到item对象
2)使用关键字yield将items提交给管道文件处理
3)在管道文件中编写代码完成数据存储的操作
4)在配置文件中开启管道操作
数据库:
基于mysql存储
基于Redis存储
代码实现流程:
1)将解析到的页面数据存储到item对象
2)使用关键字yield将items提交给管道文件处理
3)在管道文件中编写代码完成数据存储的操作
4)在配置文件中开启管道操作
思考:
如何爬取糗事百科多页面数据和将数据同时存储到磁盘文件、MySQL、Redis中?
问题一的解决方案:请求的手动发送
问题二的解决方案:
1)在管道文件中编写对应平台的管道类
2)在配置文件中对自定义的管道类进行生效操作
练习
需求:爬取糗事百科中作者和内容并基于终端指令存储
qiushi.py
1 # -*- coding: utf-8 -*-
2 import scrapy
3 class QiushiSpider(scrapy.Spider):
4 name = 'qiushi'
5 # allowed_domains = ['www.xxx.com']
6 start_urls = ['https://www.qiushibaike.com/text/']
7 def parse(self, response):
8 div_list=response.xpath('//div[@id="content-left"]/div')
9 data_list=[]
10 for div in div_list:
11 author=div.xpath('.//div[@class="author clearfix"]/a[2]/h2/text()').extract_first()
12 content=div.xpath('.//div[@class="content"]/span/text()').extract_first()
13 dict={
14 'author':author,
15 'content':content
16 }
17 data_list.append(dict)
18 return data_list
settings.py
1 USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3704.400 QQBrowser/10.4.3587.400'
2 ROBOTSTXT_OBEY = False
终端操作:

需求:爬取糗事百科中作者和内容并基于管道存储
qiushi.py
1 # -*- coding: utf-8 -*-
2 import scrapy
3 from qiushiProject.items import QiushiprojectItem
4 class QiushiSpider(scrapy.Spider):
5 name = 'qiushi'
6 # allowed_domains = ['www.xxx.com']
7 start_urls = ['https://www.qiushibaike.com/text/']
8 def parse(self, response):
9 div_list=response.xpath('//div[@id="content-left"]/div')
10 for div in div_list:
11 author=div.xpath('.//div[@class="author clearfix"]/a[2]/h2/text()').extract_first()
12 content=div.xpath('.//div[@class="content"]/span/text()').extract_first()
13 #第一步:将解析到的页面数据存储到item对象
14 item=QiushiprojectItem()
15 item['author'] = author
16 item['content'] = content
17 #第二步:使用关键字yield将items提交给管道文件处理
18 yield item
items.py
1 import scrapy
2 class QiushiprojectItem(scrapy.Item):
3 # define the fields for your item here like:
4 author = scrapy.Field() #声明属性
5 content = scrapy.Field()
pipelines.py
1 class QiushiprojectPipeline(object):
2 f=None
3 #该方法只在爬虫开始时调用一次
4 def open_spider(self,spider):
5 print('开始爬虫')
6 self.f=open('./qiushi.txt','w',encoding='utf-8')
7 #该方法可接受爬虫文件提交过来的item对象,并且对item对象中的数据进行持久化存储
8 #参数item:接受到的item对象
9 def process_item(self, item, spider):
10 # 每当爬虫文件向管道提交一次item,则该方法就会被执行一次,故open方法只需打开一次,不然只会写入最后数据
11 print('process_item被调用')
12 #取出item对象中的数据
13 author=item['author']
14 content=item['content']
15 self.f.write(author+":"+content)
16 return item
17 # 该方法只在爬虫结束时调用一次
18 def close_spider(self,spider):
19 print('爬虫结束')
20 self.f.close()
settings.py
1 USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3704.400 QQBrowser/10.4.3587.400'
2 ROBOTSTXT_OBEY = False
3 ITEM_PIPELINES = {
4 'qiushiProject.pipelines.QiushiprojectPipeline': 300,
5 }
终端指令

需求:爬取糗事百科中作者和内容并基于mysql存储
qiushi.py
1 # -*- coding: utf-8 -*-
2 import scrapy
3 from qiushiProject.items import QiushiprojectItem
4 class QiushiSpider(scrapy.Spider):
5 name = 'qiushi'
6 # allowed_domains = ['www.xxx.com']
7 start_urls = ['https://www.qiushibaike.com/text/']
8 def parse(self, response):
9 div_list=response.xpath('//div[@id="content-left"]/div')
10 for div in div_list:
11 author=div.xpath('.//div[@class="author clearfix"]/a[2]/h2/text()').extract_first()
12 content=div.xpath('.//div[@class="content"]/span/text()').extract_first()
13 #第一步:将解析到的页面数据存储到item对象
14 item=QiushiprojectItem()
15 item['author'] = author
16 item['content'] = content
17 #第二步:使用关键字yield将items提交给管道文件处理
18 yield item
items.py
1 import scrapy
2 class QiushiprojectItem(scrapy.Item):
3 # define the fields for your item here like:
4 author = scrapy.Field() #声明属性
5 content = scrapy.Field()
pipelines.py
1 import pymysql
2 class QiushiprojectPipeline(object):
3 conn=None
4 cursor=None
5 def open_spider(self,spider):
6 print('开始爬虫')
7 self.conn=pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='123456',db='qiushibaike')#链接数据库
8 def process_item(self, item, spider):
9 sql='insert into qiushi values("%s","%s")'%(item['author'],item['content'])#插入数据
10 self.cursor=self.conn.cursor()#生成游标对象
11 try:
12 self.cursor.execute(sql)#执行sql语句
13 self.conn.commit()#提交事务
14 except Exception as e:
15 print(e)
16 self.conn.rollback()
17 return item
18 def close_spider(self,spider):
19 print('爬虫结束')
20 self.cursor.close()
21 self.conn.close()
settings.py
1 USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3704.400 QQBrowser/10.4.3587.400'
2 ROBOTSTXT_OBEY = False
3 ITEM_PIPELINES = {
4 'qiushiProject.pipelines.QiushiprojectPipeline': 300,
5 }
启动MySQL数据库,创建数据库qiushibaike和表qiushi
mysql> create database qiushibaike;
mysql> use qiushibaike;
mysql> create table qiushi(author char(20),content char(255));
mysql> desc qiushi;
终端指令

查看数据库
mysql> select * from qiushi;
可视化界面

需求:爬取糗事百科中作者和内容并基于Redis存储
qiushi.py
1 # -*- coding: utf-8 -*-
2 import scrapy
3 from qiushiProject.items import QiushiprojectItem
4 class QiushiSpider(scrapy.Spider):
5 name = 'qiushi'
6 # allowed_domains = ['www.xxx.com']
7 start_urls = ['https://www.qiushibaike.com/text/']
8 def parse(self, response):
9 div_list=response.xpath('//div[@id="content-left"]/div')
10 for div in div_list:
11 author=div.xpath('.//div[@class="author clearfix"]/a[2]/h2/text()').extract_first()
12 content=div.xpath('.//div[@class="content"]/span/text()').extract_first()
13 #第一步:将解析到的页面数据存储到item对象
14 item=QiushiprojectItem()
15 item['author'] = author
16 item['content'] = content
17 #第二步:使用关键字yield将items提交给管道文件处理
18 yield item
items.py
1 import scrapy
2 class QiushiprojectItem(scrapy.Item):
3 # define the fields for your item here like:
4 author = scrapy.Field() #声明属性
5 content = scrapy.Field()
pipelines.py
1 import redis
2 class QiushiprojectPipeline(object):
3 conn=None
4 def open_spider(self,spider):
5 print('开始爬虫')
6 self.conn=redis.Redis(host='127.0.0.1',port=6379)#链接数据库
7 def process_item(self, item, spider):
8 dict={
9 'author':item['author'],
10 'content':item['content']
11 }
12 self.conn.lpush('data',str(dict))#data为列表名,前后两者必须为字符串类型
13 return item
14 def close_spider(self,spider):
15 print('爬虫结束')
settings.py
1 USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3704.400 QQBrowser/10.4.3587.400'
2 ROBOTSTXT_OBEY = False
3 ITEM_PIPELINES = {
4 'qiushiProject.pipelines.QiushiprojectPipeline': 300,
5 }
终端指令

启动Redis,并写入数据库
127.0.0.1:6379> lrange data 0 -1
可视化界面

需求:实现爬取糗事百科多页面数据和将数据同时存储到磁盘文件、MySQL、Redis中
qiushi.py
1 # -*- coding: utf-8 -*-
2 import scrapy
3 from qiushiProject.items import QiushiprojectItem
4 class QiushiSpider(scrapy.Spider):
5 name = 'qiushi'
6 # allowed_domains = ['www.xxx.com']
7 start_urls = ['https://www.qiushibaike.com/text/']
8 url='https://www.qiushibaike.com/text/page/%s/'
9 pageNum=1
10 def parse(self, response):
11 div_list=response.xpath('//div[@id="content-left"]/div')
12 for div in div_list:
13 author=div.xpath('.//div[@class="author clearfix"]/a[2]/h2/text()').extract_first()
14 content=div.xpath('.//div[@class="content"]/span/text()').extract_first()
15 item=QiushiprojectItem()
16 item['author'] = author
17 item['content'] = content
18 yield item
19 #13表示最后一页
20 if self.pageNum <= 13:
21 print('第%s页爬取成功并写入文件' % self.pageNum)
22 self.pageNum += 1
23 new_url = 'https://www.qiushibaike.com/text/page/%s/'% self.pageNum
24 yield scrapy.Request(url=new_url,callback=self.parse)
items.py
1 import scrapy
2 class QiushiprojectItem(scrapy.Item):
3 # define the fields for your item here like:
4 author = scrapy.Field() #声明属性
5 content = scrapy.Field()
pipelines.py
1 import redis
2 class QiushiprojectPipeline(object):
3 conn=None
4 def open_spider(self,spider):
5 print('开始爬虫')
6 self.conn=redis.Redis(host='127.0.0.1',port=6379)#链接数据库
7 def process_item(self, item, spider):
8 dict={
9 'author':item['author'],
10 'content':item['content']
11 }
12 self.conn.lpush('data',str(dict))#data为列表名,前后两者必须为字符串类型
13 return item
14 def close_spider(self,spider):
15 print('数据已写入Redis数据库中')
16
17 import pymysql
18 class QiushiprojectByMysql(object):
19 conn=None
20 cursor=None
21 def open_spider(self,spider):
22 print('开始爬虫')
23 self.conn=pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='123456',db='qiushibaike')
24 def process_item(self,item,spider):
25 sql='insert into qiushi values ("%s","%s")'%(item['author'],item['content'])
26 self.cursor=self.conn.cursor()
27 try:
28 self.cursor.execute(sql)
29 self.conn.commit()
30 except Exception as e:
31 print(e)
32 self.conn.rollback()
33 return item
34 def close_spider(self,spider):
35 print('数据已写入MySQL数据库中')
36 self.cursor.close()
37 self.conn.close()
38
39 class QiushiprojectByFiles(object):
40 f = None
41 def open_spider(self, spider):
42 print('开始爬虫')
43 self.f = open('./qiushi.txt', 'w', encoding='utf-8')
44 def process_item(self, item, spider):
45 author = str(item['author'])
46 content = str(item['content'])
47 self.f.write(author + ":" + content)
48 return item
49 def close_spider(self, spider):
50 print('数据已写入到磁盘文件中')
51 self.f.close()
settings.py
1 USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3704.400 QQBrowser/10.4.3587.400'
2 ROBOTSTXT_OBEY = False
3 ITEM_PIPELINES = {
4 'qiushiProject.pipelines.QiushiprojectPipeline': 300,
5 'qiushiProject.pipelines.QiushiprojectByMysql': 400,
6 'qiushiProject.pipelines.QiushiprojectByFiles': 500,
7 }
终端指令

scrapy各种持久化存储的奇淫技巧的更多相关文章
- 优化DP的奇淫技巧
DP是搞OI不可不学的算法.一些丧心病狂的出题人不满足于裸的DP,一定要加上优化才能A掉. 故下面记录一些优化DP的奇淫技巧. OJ 1326 裸的状态方程很好推. f[i]=max(f[j]+sum ...
- 12个实用的 Javascript 奇淫技巧
这里分享12个实用的 Javascript 奇淫技巧.JavaScript自1995年诞生以来已过去了16个年头,如今全世界无数的网页在依靠她完成各种关键任务,JavaScript曾在Tiobe发布的 ...
- NGINX的奇淫技巧 —— 5. NGINX实现金盾防火墙的功能(防CC)
NGINX的奇淫技巧 —— 5. NGINX实现金盾防火墙的功能(防CC) ARGUS 1月13日 发布 推荐 0 推荐 收藏 2 收藏,1.1k 浏览 文章整理中...... 实现思路 当服务器接收 ...
- NGINX的奇淫技巧 —— 3. 不同域名输出不同伺服器标识
NGINX的奇淫技巧 —— 3. 不同域名输出不同伺服器标识 ARGUS 1月13日 发布 推荐 0 推荐 收藏 6 收藏,707 浏览 大家或许会有这种奇葩的需求...要是同一台主机上, 需要针对不 ...
- NGINX的奇淫技巧 —— 6. IF实现数学比较功能 (1)
NGINX的奇淫技巧 —— 6. IF实现数学比较功能 (1) ARGUS 1月13日 发布 推荐 0 推荐 收藏 3 收藏,839 浏览 nginx的if支持=.!= 逻辑比较, 但不支持if中 & ...
- Zepto源码分析(二)奇淫技巧总结
Zepto源码分析(一)核心代码分析 Zepto源码分析(二)奇淫技巧总结 目录 * 前言 * 短路操作符 * 参数重载(参数个数重载) * 参数重载(参数类型重载) * CSS操作 * 获取属性值的 ...
- scrapy之持久化存储
scrapy之持久化存储 scrapy持久化存储一般有三种,分别是基于终端指令保存到磁盘本地,存储到MySQL,以及存储到Redis. 基于终端指令的持久化存储 scrapy crawl xxoo - ...
- javascript之奇淫技巧
最近准备面试,复习一下javascript,整理了一些javascript的奇淫技巧~ //为兼容ie的模拟Object.keys() Object.showkeys = function(obj) ...
- Gradle更小、更快构建APP的奇淫技巧
本文已获得原作者授权同意,翻译以及转载原文链接:Build your Android app Faster and Smaller than ever作者:Jirawatee译文链接:Gradle更小 ...
随机推荐
- JAVA基础语法:函数(方法)、类和对象(转载)
4.JAVA基础语法:函数(方法).类和对象 函数 在java中函数也称为方法,是一段具备某种功能的可重用代码块. 一个函数包括这几部分: 函数头 函数头包括函数访问修饰符,函数返回值类型, 函数名, ...
- 使用vimdiff做hg的版本比较工具
gvim的文本比较功能很强,命令行用法:gvim -d file1 file2,hg自带的hg diff没有颜色标示,含义也不够清晰,所以需要用vim的diff代替它,实现方法是在全局配置文件中增加: ...
- 渲染优化之CSS Containment
引言 在开始介绍今天的主角 CSS Containment 之前,我们需要了解一些前置知识回流和重绘,方便我们理解以及应用的场景. 简单回忆下回流和重绘 回流(Reflow):当浏览器必须重新处理和绘 ...
- STM32—驱动DHT11数字温湿度传感器
文章目录 DHT11模块简介 DHT11数据传输 DHT11通信时序 代码实现 相关引脚初始化 复位模块 判断响应模块 读取数据包模块 DHT11模块简介 DHT11数字温湿度传感器,用来测量环境的温 ...
- noip8
T1 星际旅行 考试时觉得是道数学题,但没想到忘了欧拉路. 首先将每条边都拆成两条边,那么题目就变成了任意删掉两条边,使得新的图中存在欧拉路.设 \(sum\) 表示自环的数量, \(du_{i}\) ...
- ES6中新增的数组知识记录
JSON数组格式转换 let json = { '0': 'hello', '1': 'I am ', '2': 'michael', length:3 } 这就是一个JSON数组格式,跟普通的JSO ...
- VS 添加自定义--代码块 实现一秒创建方法
创建一个方法 你是不是不可避免需要敲以下至少6行代码 现在教你一个方法 实现一秒创建完整方法 首先按照代码块规则创建代码块文件 代码块意义,是什么? 请参考: https://docs.microso ...
- C#串口通信SeriPort 电表DLT645 RS234/RS485
难受,三个多月前有一个电表电量监控的项目.做完了就没再管了.今天有需求需要改一些地方,但是....我想不起来干了啥,怎么干的啦.真的完全忘了.....项目名称叫啥都忘了.找了半天 不知道有没有和我一样 ...
- Flink的状态管理与恢复机制
参考地址:https://www.cnblogs.com/airnew/p/9544683.html 问题一.什么是状态? 问题二.Flink状态类型有哪几种? 问题三.状态有什么作用? 问题四.如何 ...
- 【Azure 应用服务】使用PowerShell脚本上传文件至App Service目录
问题描述 使用PowerShell脚本上传文件至App Service目录的示例 脚本示例 对文件进行上传,使用的 WebClient.UploadFile 方法进行上传.当文件夹中包含子目录,执行以 ...