scrapy資料儲存在mysql資料庫的兩種方式(同步和非同步)
阿新 • • 發佈:2020-02-20
方法一:同步操作
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) """ # 執行插入資料到資料庫操作 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,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,%s) """ self.cursor.execute(insert_sql,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,查詢更快)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。