上节我们讲到通过管道将数据存储到了本地txt文件。
scrapy爬虫利用管道存储为txt文件
那怎样存储到数据库呢?
一样是通过管道,而且只要你了解了管道的初步,就非常简单!
基于管道实现数据的备份
课程:将爬取到的数据分布存储到不同的载体
实现:将数据一份存储到mysql
,一份存储到redis
问题:管道文件中的一个管道类表示怎样的一组操作呢?
-
一个管道类对应一种形式的持久化存储操作。如果将数据存储到不同的载体中,就需要使用多个管道类
本地化存储的管道我们已经写好了。
我们先来写存储
mysql数据库
的管道
mysql数据库
存储
这里我们需要用到pymsql
模块
在pipelines.py
文件中,导入pymsql模块
import pymysql
写mysql
管道代码:
管道文件中,默认的类就是DuanziproPipeline
,也就是我们存储txt文件的类。
先回顾下DuanziproPipeline
这个类是怎么实现存储的呢?有哪些方法呢?
# 将数据存储到txt
class DuanziproPipeline:
f = None
# 重新父类的方法
def open_spider(self, spider):
print('我是open_spider(),我只会在爬虫开始的时候执行一次!')
self.f = open('duanzi.txt', 'w', encoding='utf-8')
def close_spider(self, spider):
print('我是close_spider(),我只会在爬虫结束的时候执行一次!')
self.f.close()
# 该方法是用来接收item对象.一次只能接收一个item,说明该方法会被调用多次
# 参数item:就是接收到的item对象
def process_item(self, item, spider):
# print(item) # item其实就是一个字典
# 将item存储到文本文件
self.f.write(item['title'] + ':' + item['note'] + '\n')
return item
既然本地化存储是个管道类,
那么存mysql
数据也需要再创建一个管道类,类名就是:MysqlPipeline
class MysqlPipeline():
pass
当然,三个方法也是要有的。
pymsql
模块的使用方法这里简单介绍,详细的可以自行学习。
- 连接数据库
# 将数据存储到mysql
class MysqlPipeline():
# 数据库连接
coon = None
# 游标变量
cursor = None
def open_spider(self, spider):
# 通过pymysql连接数据库
# host:数据库地址 port:端口 user:用户名 password:密码 db:数据库名字 chaeset:编码
self.coon = pymysql.Connect(host='127.0.0.1', port=3306, user='root', password='123456', db='spider',
charset='utf8')
# 打印连接
print(self.coon)
-
存储过程
def process_item(self, item, spider): self.cursor = self.coon.cursor() # 写sql语句 sql = 'insert into duanzi values ("%s","%s") ' % (item['title'], item['note']) # 事务处理 try: self.cursor.execute(sql) self.coon.commit() except Exception as e: print(e) self.coon.rollback() return item
-
关闭数据库
def close_spider(self, spider): self.cursor.close() self.coon.close()
这样,mysql
管道存储就写好了,爬虫文件和items.py
根本无需再修改,因为管道接收的就是item对象
settings.py
一定要记得修改配置文件
管道每一个类对应一个管道优先级,优先级区分开来。记得类名不要写错
运行一下,就会看到存储到了数据库里。
如果错误,说明pymsql
或数据库有问题,仔细排查
Redis存储
mysql
会了,Redis
也是一样的代码:
from redis import Redis
# 将数据写入redis
class RedisPipeline():
conn = None
def open_spider(self, spider):
self.conn = Redis(host='127.0.0.1', port=6379)
print(self.conn)
def process_item(self, item, spider):
# 报错:将redis模块的版本指定城2.10.6即可。 pip install -U redis==2.10.6
self.conn.lpush('duanzi', item)
return item
注意
已经定义好了三个管道类,将数据写入到三个载体中进行存储:
-
item会不会依次提交给三个管道类?
-
不会,爬虫文件中的item只会被提交给优先级最高的那一个管道类
-
优先级高的管道类需要在process_item中实现return item,就是item传递给下一个即将被执行的管道类
-
也就是说,每一个
process_item
方法中,必须要有return item
,才可以传递给下一个管道类ef process_item(self, item, spider): xxx return item
-
-
关注Python涛哥!学习更多Python知识!