【Python爬蟲】 輕鬆幾步 將 scrapy 框架 獲取得到的 資料 儲存到 MySQL 資料庫中
阿新 • • 發佈:2019-02-14
以下操作 是在 一個 完整的 scrapy 專案中 新增 程式碼:
中介軟體 和 spiders 中的程式碼 都不需要修改 只需要 做下面兩件事就可以將資料儲存到資料庫了,不過在寫程式碼之前 我們要先:
-
在終端 執行命令:net start mysql57 開啟 mysql 伺服器
-
建立資料庫,在資料庫中建立與要儲存相關的資料的表(名稱要與框架中的名稱一樣, 表中建立的 欄位名稱 也要跟 框架中 需要儲存欄位 名 一致)(利用圖形化介面工具建立起來方便些:Navicat Premium)
-
建立好資料庫和表之後 先測試一下 資料庫能否連線成功
'''
測試資料庫是否連線成功
'''
import pymysql
conn=pymysql.connect(host='127.0.0.1',port=3306,user='資料庫名稱',password='資料庫密碼',db='表名',charset='utf8')
print(conn)
輸出結果為:<pymysql.connections.Connection object at 0x000000000220D7B8>
則表示資料庫連線成功 如果報錯則失敗
當資料庫連線成功了之後, 接下來 我們就開始在scrappy框架中進 "裝修" :
1:配置環境 在setting檔案中加入: sql資料庫引數 和 pipelines管道配置:
# 設定管道中類的優先順序
ITEM_PIPELINES = {
'movie.pipelines.MoviePipeline': 300, # 管道中自帶的類,優先順序預設第一
'movie.pipelines.MovieMysqlPipeline': 200, # 管道中 新建的類 用來儲存資料到資料庫
}
# 連線資料庫
# 填的 是所儲存資料庫的資訊
DB_HOST = '127.0.0.1'
DB_PORT = 3306
DB_USER = '使用者名稱'
DB_PASSWORD = '密碼'
# 資料庫名稱
DB_DB = 'movies'
DB_CHARSET = 'utf8'
2 : 管道中 新建一個類 用來儲存資料到資料庫 :
(下面程式碼中 關於資料庫的一下東西是博主自己 , 請自行修改 )
import pymysql
from scrapy.utils.project import get_project_settings
# 儲存資料到mysql資料庫(資料去重)
class WeimobMysqlPipeline(object):
def __init__(self):
setting = get_project_settings()
self.host = setting.get("DB_HSOT")
self.port = setting.get("DB_PORT")
self.user = setting.get("DB_USER")
self.password = setting.get("DB_PASSWORD")
self.db = setting.get("DB_DB")
self.charset = setting.get("DB_CHARSET")
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, db=self.db, charset=self.charset)
# 建立遊標 通過cursor 執行 sql語句
self.cursor = self.conn.cursor()
def process_item(self, item, spider):
try:
# 查重處理
self.cursor.execute('select * from agents where agent = %s and agent_company= %s',(item['agent'], item['agent_company']))
# 檢視是否有重複的資料
repetition = self.cursor.fetchone()
#重複
if repetition:
# 列印一下
print('資料重複',item['agent'],item['agent_company'])
else:
# 插入資料
self.cursor.execute('insert into agents(agent,agent_company) values("%s","%s") '%(item['agent'],item['agent_company']))
#提交sql語句
self.conn.commit()
except Exception as error:
print(error)
return item
def close_spider(self, spider):
# 關閉 遊標
self.cursor.close()
# 關閉 連線
self.conn.close()