1. 程式人生 > >Scrapy爬蟲資料存資料庫

Scrapy爬蟲資料存資料庫

這裡的爬蟲程式碼是基於第一個爬蟲程式【重寫第一個爬蟲程式】,由於是python3.6.4,所以不能使用mysqldb,那就採用pymysql。

一、安裝並測試pymysql

pip install pymysql

在python cli下測試是否安裝成功

>>> import pymysql
>>>

測試與本地mysql資料庫連線情況

>>> conn =pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root',db='scrapy')
>>>

執行一個簡單查詢

>>> cursor = conn.cursor()
>>> cursor.execute('select * from images')
38    #有38條記錄
>>>

說明pymysql安裝成功

二、程式碼實現

1 在settings.py中增加資料庫連線配置

#mysql資料庫配置
DB_CONFIG = {
	'MYSQL_HOST':'localhost',
	'MYSQL_DBNAME': 'scrapy',
	'MYSQL_USER': 'root',
	'MYSQL_PASSWD': 'root',
	'MYSQL_PORT': 3306,
    'MYSQL_CHARSET': 'utf8'
}

2 image下建立db/dbhelper.py目錄檔案

# -*- coding: utf-8 -*-

import pymysql
from image.settings import DB_CONFIG

class DBHelper():
    '''
    讀取settings中的配置,實現資料庫操作
    '''
    def __init__(self):
        self.connect = pymysql.connect(
            host=DB_CONFIG['MYSQL_HOST'],
            db=DB_CONFIG['MYSQL_DBNAME'],
            user=DB_CONFIG['MYSQL_USER'],
            passwd=DB_CONFIG['MYSQL_PASSWD'],
            charset=DB_CONFIG['MYSQL_CHARSET'],
            port=DB_CONFIG['MYSQL_PORT']
        )

        self.cursor = self.connect.cursor()

    #插入資料庫
    def insert(self, item):
        try:
            cursor = self.cursor
            sql = "insert into images(title,img_url) values(%s,%s)"
            #呼叫插入的方法
            cursor.execute(sql, (
                item["title"], item['url']
                )
            )
            self.db.commit()

        except Exception as e:
            print('insert error', e)
            self.db.rollback()
        finally:
            self.db.close()

        return item

3 修改pipeline.py檔案
註釋原來的儲存檔案程式碼,實現儲存mysql

import json
from image.db.dbhelper import DBHelper

class ImagePipeline(object):
	def __init__(self):
		#self.file = open('data.json', 'wb')
		self.db = DBHelper()

	def process_item(self, item, spider):
		#存檔案
		#line = json.dumps(dict(item)) + "\n"
		#self.file.write(line.encode())

		#存資料庫試試
		self.db.insert(item)
		return item


4 其他

表建立

mysql> show create table images;
+--------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table  | Create Table                                                                                                                                                                                                                                                                      |
+--------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| images | CREATE TABLE `images` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `title` varchar(64) DEFAULT '' COMMENT '標題',
  `img_url` varchar(100) DEFAULT '' COMMENT '圖片url',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

本文主要是將item資料持久化到mysql資料庫,後續文章會考慮寫一些python web開發,安全等方面的內容。歡迎留言交流學習。