import pymysql
from redis import Redis
# 持久化数据到mysql
class QiubaiproPipeline(object):
# 创建sql连接
conn = None
# 创建sql游标
cursor = None
# 爬虫开始执行,创建mysql连接
def open_spider(self, spider):
self.conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="1234", db="spider")
# 持久化存储
def process_item(self, item, spider):
# 创建游标
self.cursor = self.conn.cursor()
# 获取数据属性
author = item["author"]
content = item["content"]
print(author, content)
sql = "insert into qiushipro values('%s','%s')"%(author, content)
try:
# 执行sql语句
self.cursor.execute(sql)
# 事务提交
self.conn.commit()
except Exception as e:
# 打印错误信息
print(e)
# 事务回滚
self.conn.rollback()
self.cursor.close()
# 返回item对象到管道,供下一个管道类接收
return item
# 关闭数据库游标与连接
def close_spider(self, spider):
# self.cursor.close()
self.conn.close()
# 持久化数据到redis
class RedisPipeline(object):
# 创建redis连接
conn = None
# 爬虫开始执行,创建mysql连接
def open_spider(self, spider):
self.conn = Redis(host="127.0.0.1", port=6379, db=0)
# 持久化存储
def process_item(self, item, spider):
# 获取数据属性
author = item["author"]
content = item["content"]
# 创建存储的数据结构
data = {
"author": author,
"content": content
}
# 在redis数据库中创建一个键为qiushibaike的队列,值为一个列表,由左向右压栈
self.conn.lpush("qiushibaike", data)
# 返回item对象到管道,供下一个管道类接收
return item
配置文件:settings.py
# 开启管道
ITEM_PIPELINES = {
'qiubaiPro.pipelines.QiubaiproPipeline': 300, #优先级 数字越小,优先级越高,越先执行
'qiubaiPro.pipelines.RedisPipeline': 400,
}
优质内容筛选与推荐>>
1、POJ1274-The Perfect Stall2、Overture里如何添加震音记号3、五月工作总结4、Node.js 常用工具5、Redis主从复制
长按二维码向我转账
受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。