(六--二)scrapy框架之持久化操作
scrapy框架之持久化操作
- 基于终端指令的持久化存储
- 基于管道的持久化存储
1 基于终端指令的持久化存储
- 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作。
执行输出指定格式进行存储:将爬取到的数据写入不同格式的文件中进行存储
scrapy crawl 爬虫名称 -o xxx.json
scrapy crawl 爬虫名称 -o xxx.xml
scrapy crawl 爬虫名称 -o xxx.csv
以爬取糗事百科(https://www.qiushibaike.com/text/)为例
import scrapy class QiubaiSpider(scrapy.Spider):
name = 'qiubai' # 表示该爬虫文件的名称
allowed_domains = ['www.qiushibaike.com/text/']
start_urls = ['https://www.qiushibaike.com/text/']
# 解析函数
def parse(self, response): # response就是对起始url发起请求后,对应的响应对象
author_list = response.xpath('//div[@id="content-left"]/div') all_data = []
for div in author_list:
# extract_first()可以将xpath返回列表中第一个列表元素进行extract解析操作
author = div.xpath('./div/a[2]/h2/text()').extract_first()
# extract()可以将Selector对象中存储的数据进行解析操作
author = div.xpath('./div/a[2]/h2/text()').extract()
content = div.xpath('./a/div/span/text()').extract_first() dict={
'author':author,
'content':content
}
all_data.append(dict)
return all_data # 可迭代的对象
在终端写入
执行输出指定格式进行存储:将爬取到的数据写入不同格式的文件中进行存储
scrapy crawl 爬虫名称 -o xxx.json
scrapy crawl 爬虫名称 -o xxx.xml
scrapy crawl 爬虫名称 -o xxx.csv
2 基于管道的持久化存储
scrapy框架中已经为我们专门集成好了高效、便捷的持久化操作功能,我们直接使用即可。要想使用scrapy的持久化操作功能,我们首先来认识如下两个文件:
items.py:数据结构模板文件。定义数据属性。
pipelines.py:管道文件。接收数据(items),进行持久化操作。 持久化流程:
1.爬虫文件爬取到数据后,需要将数据封装到items对象中。
2.使用yield关键字将items对象提交给pipelines管道进行持久化操作。
3.在管道文件中的process_item方法中接收爬虫文件提交过来的item对象,然后编写持久化存储的代码将item对象中存储的数据进行持久化存储
4.settings.py配置文件中开启管道
1 爬虫文件qiubai.py
# -*- coding: utf- -*-
import scrapy
from ..items import FirstProjectItem
'''基于管道存储''' '''
爬虫文件中解析数据
【items.py】将解析到的数据值全部分装在item对象中
pipelines.py
settings.py配置文件 '''
class QiubaiSpider(scrapy.Spider):
name = 'qiubai'
allowed_domains = ['www.qiushibaike.com/text/']
start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): author_list = response.xpath('//div[@id="content-left"]/div') for div in author_list: author = div.xpath('./div/a[2]/h2/text()').extract_first()
# author = div.xpath('./div/a[2]/h2/text()')[].extract()
content = div.xpath('./a/div/span/text()').extract_first()
----------------------------------------------------
items = FirstProjectItem() items["author"] = author 重点
items["content"] = content
# 提交给管道
yield items
----------------------------------------------------
2 items.py
import scrapy # items会实例化一个items对象; 用来存储解析到的数据值 class FirstProjectItem(scrapy.Item):
# define the fields for your item here like:
-----------------------------------------
author = scrapy.Field()
content = scrapy.Field() 重点 你在第一步中有几个要持久化的这就写上对应的
-----------------------------------------
3 pipelines.py
# 爬虫文件每向管道提交一次item则process_item方法就会被执行一次
class FirstProjectPipeline(object):
# item就是爬虫文件提交过来的
def process_item(self, item, spider):
return item
4 settings.py
# 第67行
ITEM_PIPELINES = {
'first_project.pipelines.FirstProjectPipeline': ,
}
依据上面四步我们就学会了基本的“基于管道的持久化”的步骤,但是我们要在piplines.py做一些操作
只是修改第3步pipelines.py
# -*- coding: utf- -*- # 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 FirstProjectPipeline(object):
# 每次都会打开多次文件,我们重写 open_spider方法来开文件一次
fp = None
def open_spider(self, spider):
print('开始爬虫')
self.fp = open('qiubai1.txt', 'w', encoding='utf-8') def process_item(self, item, spider): self.fp.write(item['author']+':'+item["content"]+"\n") # 生成qiubai1.txt文件
return item def close_spider(self,spider):
print('结束爬虫')
self.fp.close()
3 写入数据库
import pymysql
class MysqlPipline(object):
cursor = None
conn = None
def open_spider(self, spider):
print('mysql开始')
self.conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', port=3306, db='s18',charset='utf8')
def process_item(self, item, spider):
sql = "insert into t_qiubai VALUES ('%s','%s')"%(item["author"], item["content"])
self.cursor = self.conn.cursor()
try:
self.cursor.execute(sql)
self.conn.commit()
except Exception as e:
self.conn.rollback()
return item def close_spider(self, spider):
print('mysql结束')
self.cursor.close()
self.conn.close()
settings.py
ITEM_PIPELINES = {
'first_project.pipelines.FirstProjectPipeline': ,
'first_project.pipelines.MysqlPipline': , # settings 配置 值越小 越优先
}
4 写入redis数据库
import redis
class RedisPipline(object):
r = None
def open_spider(self, spider):
print('redis开始')
self.r = redis.Redis(host='127.0.0.1', port=6379)
def process_item(self, item, spider):
dict = {
'author':item['author'],
'content':item['content']
}
self.r.lpush('data', dict)
return item
def close_spider(self, spider):
print('redis结束')
settings.py设置
ITEM_PIPELINES = {
'first_project.pipelines.FirstProjectPipeline': 300,
'first_project.pipelines.RedisPipline': 500,
}
我们可以去redis里面查看
key * # 查看所有的key
lrange key 0 -1 # 从头到尾查看key
(六--二)scrapy框架之持久化操作的更多相关文章
- scrapy框架之持久化操作
1.基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作. 执行输出指定格式进行存储: ...
- 爬虫开发8.scrapy框架之持久化操作
今日概要 基于终端指令的持久化存储 基于管道的持久化存储 今日详情 1.基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的 ...
- scrapy框架之分布式操作
分布式概念 分布式爬虫: 1.概念:多台机器上可以执行同一个爬虫程序,实现网站数据的分布爬取. 2.原生的scrapy是不可以实现分布式爬虫? a)调度器无法共享 b)管道无法共享 3.scrapy- ...
- 6 scrapy框架之分布式操作
分布式爬虫 一.redis简单回顾 1.启动redis: mac/linux: redis-server redis.conf windows: redis-server.exe redis-wi ...
- scrapy框架的持久化存储
一 . 基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作. 执行输出指定格式进行存 ...
- 爬虫开发14.scrapy框架之分布式操作
分布式爬虫 一.redis简单回顾 1.启动redis: mac/linux: redis-server redis.conf windows: redis-server.exe redis-wi ...
- scrapy框架之CrawlSpider操作
提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...
- 爬虫开发11.scrapy框架之CrawlSpider操作
提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...
- Scrapy 框架,持久化文件相关
持久化相关 相关文件 items.py 数据结构模板文件.定义数据属性. pipelines.py 管道文件.接收数据(items),进行持久化操作. 持久化流程 1.爬虫文件爬取到数据后,需要将数据 ...
随机推荐
- 基于IntelliJ IDEA的代码评审插件 Code Review Plugin
一.阿里规范公约 1.左上角 File -> Settings -> Plugins -> 搜索:Alibaba Java Coding Guidelines,安装插件并重启IDEA ...
- 修剪草坪 HYSBZ - 2442
在一年前赢得了小镇的最佳草坪比赛后,FJ变得很懒,再也没有修剪过草坪.现在,新一轮的最佳草坪比赛又开始了,FJ希望能够再次夺冠. 然而,FJ的草坪非常脏乱,因此,FJ只能够让他的奶牛来完成这项工作.F ...
- 「BJWC2012」冻结
传送门 Luogu 解题思路 分层图最短路,层与层之间的边的边权减半,然后就是板子了. 细节注意事项 咕咕咕. 参考代码 #include <algorithm> #include < ...
- 通过注册码破解IntelliJ IDEA
把激活码填入下面的地方即可.如果不知道在哪里,那么就选菜单栏里的help再选Register就会弹出下面的界面 激活码网址里面有 lookdiv.com 里面的钥匙就是lookdiv.com
- 说说我对SQL语句执行顺序的理解,以SQL Server为例
有人说SQL语句难学,其实并不难!只要掌握了基本的语句执行顺序,用程序化的思维分析结构,再难的问题也会迎刃而解! 假设有如下表emp 现在要求 列出员工姓名(ename)中不含A的所有人按照部门编号( ...
- 【QSBOJ】字符串编辑
题目链接:https://bbs.csdn.net/topics/390289884?page=1 AC代码: #include<bits/stdc++.h> using namespac ...
- ObjectMapper : can only instantiate non-static inner class by using default, no-argument constructor
Label_t lTrain = new ObjectMapper().readValue(s, Label_t.class); 因为Label_t是内部类,需要 1.static 2.无参构造函数
- 怎样快速高效的定义Django的序列化器
1.使用Serializer方法自己创建一个序列化器 先写一个简单的例子 class BookInfoSerializer(serializers.Serializer): ""& ...
- Linux 内核 编译模块
背景: 由于调试内核或者由于分区大小限制,有时候内核组件不一定完全需要编进内核中. 所以,在开发中经常将内核组件编译成为模块,等到在恰当的时机加载. 概览: Linux内核模块的编译方法有两种: 1. ...
- P1067 试密码
P1067 试密码 转跳点: