scrapy數(shù)據(jù)存儲在mysql數(shù)據(jù)庫的兩種方式(同步和異步)
方法一:同步操作
1.pipelines.py文件(處理數(shù)據(jù)的python文件)
import pymysql
class LvyouPipeline(object):
def __init__(self):
# connection database
self.connect = pymysql.connect(host='XXX', user='root', passwd='XXX', db='scrapy_test') # 后面三個依次是數(shù)據(jù)庫連接名、數(shù)據(jù)庫密碼、數(shù)據(jù)庫名稱
# get cursor
self.cursor = self.connect.cursor()
print("連接數(shù)據(jù)庫成功")
def process_item(self, item, spider):
# sql語句
insert_sql = """
insert into lvyou(name1, address, grade, score, price) VALUES (%s,%s,%s,%s,%s)
"""
# 執(zhí)行插入數(shù)據(jù)到數(shù)據(jù)庫操作
self.cursor.execute(insert_sql, (item['Name'], item['Address'], item['Grade'], item['Score'],
item['Price']))
# 提交,不進(jìn)行提交無法保存到數(shù)據(jù)庫
self.connect.commit()
def close_spider(self, spider):
# 關(guān)閉游標(biāo)和連接
self.cursor.close()
self.connect.close()
2.配置文件中

方式二 異步儲存
pipelines.py文件:
通過twisted實(shí)現(xiàn)數(shù)據(jù)庫異步插入,twisted模塊提供了 twisted.enterprise.adbapi
1. 導(dǎo)入adbapi
2. 生成數(shù)據(jù)庫連接池
3. 執(zhí)行數(shù)據(jù)數(shù)據(jù)庫插入操作
4. 打印錯誤信息,并排錯
import pymysql
from twisted.enterprise import adbapi
# 異步更新操作
class LvyouPipeline(object):
def __init__(self, dbpool):
self.dbpool = dbpool
@classmethod
def from_settings(cls, settings): # 函數(shù)名固定,會被scrapy調(diào)用,直接可用settings的值
"""
數(shù)據(jù)庫建立連接
:param settings: 配置參數(shù)
:return: 實(shí)例化參數(shù)
"""
adbparams = dict(
host=settings['MYSQL_HOST'],
db=settings['MYSQL_DBNAME'],
user=settings['MYSQL_USER'],
password=settings['MYSQL_PASSWORD'],
cursorclass=pymysql.cursors.DictCursor # 指定cursor類型
)
# 連接數(shù)據(jù)池ConnectionPool,使用pymysql或者M(jìn)ysqldb連接
dbpool = adbapi.ConnectionPool('pymysql', **adbparams)
# 返回實(shí)例化參數(shù)
return cls(dbpool)
def process_item(self, item, spider):
"""
使用twisted將MySQL插入變成異步執(zhí)行。通過連接池執(zhí)行具體的sql操作,返回一個對象
"""
query = self.dbpool.runInteraction(self.do_insert, item) # 指定操作方法和操作數(shù)據(jù)
# 添加異常處理
query.addCallback(self.handle_error) # 處理異常
def do_insert(self, cursor, item):
# 對數(shù)據(jù)庫進(jìn)行插入操作,并不需要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、報(bào)錯pymysql.err.ProgrammingError: (1064, ……
原因:當(dāng)item['quotes']里面含有引號時,可能會報(bào)上述錯誤
解決辦法:使用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、每執(zhí)行一次爬蟲,就會將數(shù)據(jù)追加到數(shù)據(jù)庫中,如果多次的測試爬蟲,就會導(dǎo)致相同的數(shù)據(jù)不斷累積,怎么實(shí)現(xiàn)增量爬???
- scrapy-deltafetch
- scrapy-crawl-once(與1不同的是存儲的數(shù)據(jù)庫不同)
- scrapy-redis
- scrapy-redis-bloomfilter(3的增強(qiáng)版,存儲更多的url,查詢更快)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳細(xì)整理python 字符串(str)與列表(list)以及數(shù)組(array)之間的轉(zhuǎn)換方法
這篇文章主要介紹了詳細(xì)整理python 字符串(str)與列表(list)以及數(shù)組(array)之間的轉(zhuǎn)換方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Python MySQL如何通過Binlog獲取變更記錄恢復(fù)數(shù)據(jù)
本文介紹了如何使用Python和pymysqlreplication庫通過MySQL的二進(jìn)制日志(Binlog)獲取數(shù)據(jù)庫的變更記錄,并展示了一個簡單的Python腳本,該腳本讀取Binlog事件并打印出插入、更新和刪除操作的SQL語句,此外,還提到可以使用pandas將結(jié)果輸出到Excel表格中進(jìn)行數(shù)據(jù)分析處理2025-01-01
對pytorch中x = x.view(x.size(0), -1) 的理解說明
這篇文章主要介紹了對pytorch中x = x.view(x.size(0), -1) 的理解說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
PIL包中Image模塊的convert()函數(shù)的具體使用
這篇文章主要介紹了PIL包中Image模塊的convert()函數(shù)的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
Python獲取Redis所有Key以及內(nèi)容的方法
今天小編就為大家分享一篇Python獲取Redis所有Key以及內(nèi)容的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02
詳解Python中數(shù)據(jù)類型的轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了Python中數(shù)據(jù)類型轉(zhuǎn)換的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的參考價值,感興趣的小伙伴可以了解一下2023-03-03

