天天看點

【Python爬蟲】 輕松幾步 将 scrapy 架構 擷取得到的 資料 存儲到 MySQL 資料庫中

以下操作 是在 一個 完整的  scrapy 項目中 添加 代碼:

        中間件 和 spiders 中的代碼 都不需要修改 隻需要 做下面兩件事就可以将資料儲存到資料庫了,不過在寫代碼之前 我們要先: 

  1.    在終端 執行指令:net start mysql57    開啟 mysql 伺服器 
  2.     建立資料庫,在資料庫中建立與要儲存相關的資料的表(名稱要與架構中的名稱一樣, 表中建立的 字段名稱 也要跟 架構中 需要儲存字段 名 一緻)(利用圖形化界面工具建立起來友善些:Navicat Premium)
  3.  建立好資料庫和表之後  先測試一下 資料庫能否連接配接成功
'''
測試資料庫是否連接配接成功
'''
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()
           

經過一番的 '裝修'  現在我們就能把 擷取地帶的目标資料 存儲到 自己的 資料庫中了

繼續閱讀