1. 程式人生 > >python---scrapy之MySQL同步存儲

python---scrapy之MySQL同步存儲

相關操作 ces comment 操作數 字典 爬取 drop pre var

假設我們已經能獲取到item裏定義的字段的數據,接下來就需要保存item的數據到mysql數據庫.

pipeline用來存儲item中的數據,將爬取到的數據進行二次處理

首先,要做的準備的工作,安裝MySQLdb,我安裝的是Python-MySQL1.2.5模塊.

自定義一個pipeline用mysql來存儲item中的數據

class MySQLPipeline(object):
    #自定義一個pipeline用mysql來存儲item中的數據
    def __init__(self):
        # 代碼連接數據庫
        # 1)連接
        # 連接的數據庫必須存在
db = MySQLdb.Connect(host=localhost, user=root, passwd=123456, db=testdb, charset=utf8,use_unicode=True) # 遊標/指針 cursor = db.cursor() self.db=db self.cursor=cursor #先刪除表 sql="drop table IF EXISTS test" self.cursor.execute(sql) self.db.commit() sql
= "create table if not exists test (id INT PRIMARY KEY auto_increment NOT NULL , title VARCHAR(50) NOT NULL,category_name VARCHAR (100),date_time VARCHAR (20) NOT NULL ,likes INT DEFAULT 0,content longtext ,comment INT DEFAULT 0,collect INT DEFAULT 0,detail_url VARCHAR (255) UNIQUE,src VARCHAR (255))" #
參數1:query,填寫sql語句 # 參數2:args,參數,默認是空,填寫元組 self.cursor.execute(sql) self.db.commit() def process_item(self, item, spider): #2)執行相關操作 # #3)關閉連接,先關cursor,再關db # cursor.close() # db.close() #如果要給所有列添加數據,列名可以不寫 try: sql="insert into test (title,category_name, date_time,likes,content, comment,collect, detail_url,src) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)" self.cursor.execute(sql, (item[title],item[category_name],item[date_time],item[likes], item[content],item[comment], item[collect],item[detail_url],item[src][0])) self.db.commit() except: print u數據重復忽略不計 return item def __del__(self): self.cursor.close() self.db.close()

process_item(self,item,spider)這個方法會被每個item pipeline組件調用,並且該方法必須返回一個字典數據,item或者拋出一個DropItem異常.

在settings註冊下

ITEM_PIPELINES = {

    #MySQL同步寫入
    "JobboleSpider.pipelines.MySQLPipeline": 2,


}

還有可以直接通過模型對象操作數據庫的方式稱為ORM

特點:不需要寫sql語句,可以直接操作數據庫

添加:item.save(),

刪除:item.delete()

............................

python---scrapy之MySQL同步存儲