scrapy数据存储在mysql数据库的两种方式(同步和异步)
作者:侠客云 时间:2023-07-10 03:29:43
方法一:同步操作
1.pipelines.py文件(处理数据的python文件)
import pymysql
class LvyouPipeline(object):
def __init__(self):
# connection database
self.connect = pymysql.connect(host='XXX', user='root', passwd='XXX', db='scrapy_test') # 后面三个依次是数据库连接名、数据库密码、数据库名称
# get cursor
self.cursor = self.connect.cursor()
print("连接数据库成功")
def process_item(self, item, spider):
# sql语句
insert_sql = """
insert into lvyou(name1, address, grade, score, price) VALUES (%s,%s,%s,%s,%s)
"""
# 执行插入数据到数据库操作
self.cursor.execute(insert_sql, (item['Name'], item['Address'], item['Grade'], item['Score'],
item['Price']))
# 提交,不进行提交无法保存到数据库
self.connect.commit()
def close_spider(self, spider):
# 关闭游标和连接
self.cursor.close()
self.connect.close()
2.配置文件中
方式二 异步储存
pipelines.py文件:
通过twisted实现数据库异步插入,twisted模块提供了 twisted.enterprise.adbapi
1. 导入adbapi
2. 生成数据库连接池
3. 执行数据数据库插入操作
4. 打印错误信息,并排错
import pymysql
from twisted.enterprise import adbapi
# 异步更新操作
class LvyouPipeline(object):
def __init__(self, dbpool):
self.dbpool = dbpool
@classmethod
def from_settings(cls, settings): # 函数名固定,会被scrapy调用,直接可用settings的值
"""
数据库建立连接
:param settings: 配置参数
:return: 实例化参数
"""
adbparams = dict(
host=settings['MYSQL_HOST'],
db=settings['MYSQL_DBNAME'],
user=settings['MYSQL_USER'],
password=settings['MYSQL_PASSWORD'],
cursorclass=pymysql.cursors.DictCursor # 指定cursor类型
)
# 连接数据池ConnectionPool,使用pymysql或者Mysqldb连接
dbpool = adbapi.ConnectionPool('pymysql', **adbparams)
# 返回实例化参数
return cls(dbpool)
def process_item(self, item, spider):
"""
使用twisted将MySQL插入变成异步执行。通过连接池执行具体的sql操作,返回一个对象
"""
query = self.dbpool.runInteraction(self.do_insert, item) # 指定操作方法和操作数据
# 添加异常处理
query.addCallback(self.handle_error) # 处理异常
def do_insert(self, cursor, item):
# 对数据库进行插入操作,并不需要commit,twisted会自动commit
insert_sql = """
insert into lvyou(name1, address, grade, score, price) VALUES (%s,%s,%s,%s,%s)
"""
self.cursor.execute(insert_sql, (item['Name'], item['Address'], item['Grade'], item['Score'],
item['Price']))
def handle_error(self, failure):
if failure:
# 打印错误信息
print(failure)
注意:
1、python 3.x 不再支持MySQLdb,它在py3的替代品是: import pymysql。
2、报错pymysql.err.ProgrammingError: (1064, ……
原因:当item['quotes']里面含有引号时,可能会报上述错误
解决办法:使用pymysql.escape_string()方法
例如:
sql = """INSERT INTO video_info(video_id, title) VALUES("%s","%s")""" % (video_info["id"],pymysql.escape_string(video_info["title"]))
3、存在中文的时候,连接需要添加charset='utf8',否则中文显示乱码。
4、每执行一次爬虫,就会将数据追加到数据库中,如果多次的测试爬虫,就会导致相同的数据不断累积,怎么实现增量爬取?
scrapy-deltafetch
scrapy-crawl-once(与1不同的是存储的数据库不同)
scrapy-redis
scrapy-redis-bloomfilter(3的增强版,存储更多的url,查询更快)
来源:https://www.cnblogs.com/knighterrant/p/10783634.html
标签:scrapy,mysql
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 实现OpenCV格式和PIL.Image格式互转
2021-08-03 03:41:42
python之pymysql模块简单应用示例代码
2024-01-22 00:22:45
Flask框架模板渲染操作简单示例
2023-06-07 00:02:45
javascript制作loading动画效果 loading效果
2024-02-26 18:50:24
![](https://img.aspxhome.com/file/2023/4/56224_0s.gif)
MySQL安装后不能用是什么情况该如何解决
2024-01-25 10:53:38
sql server 性能优化之nolock
2024-01-24 11:34:10
![](https://img.aspxhome.com/file/2023/6/128396_0s.png)
超详细教你怎么升级Mysql的版本
2024-01-28 02:36:20
![](https://img.aspxhome.com/file/2023/8/107708_0s.png)
手把手教你python实现SVM算法
2022-04-22 09:29:06
![](https://img.aspxhome.com/file/2023/0/88910_0s.gif)
MySQL中锁的相关问题
2024-01-13 09:49:33
![](https://img.aspxhome.com/file/2023/3/71773_0s.png)
Vue2.0 axios前后端登陆拦截器(实例讲解)
2023-07-02 16:59:11
![](https://img.aspxhome.com/file/2023/9/139869_0s.jpg)
JavaScript判断微信浏览器实例代码
2024-04-18 09:30:31
pandas返回缺失值位置的方法实例教程
2022-11-13 01:51:31
![](https://img.aspxhome.com/file/2023/7/69607_0s.png)
Python如何输出整数
2022-03-30 07:19:35
![](https://img.aspxhome.com/file/2023/4/100944_0s.png)
ASP 下载时重命名已上传文件的新下载文件名的实现代码
2012-11-30 20:33:45
Playwright快速上手指南(入门教程)
2022-09-25 02:44:23
mysql分页的limit参数简单示例
2024-01-19 05:58:31
![](https://img.aspxhome.com/file/2023/2/119752_0s.png)
浅析Python字符串索引、切片、格式化
2023-09-26 07:57:20
![](https://img.aspxhome.com/file/2023/9/134579_0s.png)
Go语言实现的web爬虫实例
2023-07-21 02:35:57
Python Excel处理库openpyxl详解
2021-10-18 13:59:04
使用pandas计算环比和同比的方法实例
2021-02-15 18:06:34
![](https://img.aspxhome.com/file/2023/1/92331_0s.png)