Scrapy連接MySQL數據庫

一、Mysql安裝
3.4以上安裝命令:pip install PyMySQL
3.4以下安裝命令:pip install MySQLdb

二、Mysql的使用

在pipelines.py文件引入MySQL,引入命令import pymysql.cursors。引入之後,就可以編寫具體的類了,首先我們需要創建數據庫的連接,創建數據庫連接之前,需要確保你已經成功安裝了MySQL並且已經在MySQL裏面創建好了表、字段,並且MySQL已經啓動。


1、創建數據庫連接
def __init__(self):
        # 連接數據庫
        self.connect = pymysql.connect(
            host='127.0.0.1',#數據庫地址
            port=3306,# 數據庫端口
            db='scrapyMysql', # 數據庫名
            user = 'root', # 數據庫用戶名
            passwd='root', # 數據庫密碼
            charset='utf8', # 編碼方式
            use_unicode=True)

        # 通過cursor執行增刪查改
        self.cursor = self.connect.cursor()

2、實現mysql的入庫

def process_item(self, item, spider):

        self.cursor.execute(
            """insert into chuanke(name, type, view, price ,teacher, url)
            value (%s, %s, %s, %s, %s, %s)""",#純屬python操作mysql知識,不熟悉請惡補
            (item['name'],# item裏面定義的字段和表字段對應
             item['type'],
             item['view'],
             item['price'],
             item['teacher'],
             item['url']))

        # 提交sql語句
        self.connect.commit()

        return item#必須實現返回

3、settings.py裏面開啓MySQLPipline

ITEM_PIPELINES = {
    'scrapyMysql.MySQLPipeline.MySQLPipeline': 1,
     #格式爲:'項目名.文件名.類名':優先級(越小越大)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章