1. 程式人生 > >scrapy框架 基於mysql資料庫儲存資料方法、案例

scrapy框架 基於mysql資料庫儲存資料方法、案例

流程思路

  1. 將解析資料存到items物件
  2. 使用yield 將items交給管道檔案處理
  3. 在管道檔案pipelines編寫程式碼儲存到資料庫
  4. 在setting配置檔案開啟管道

案例

items中

  • 按照格式定義欄位
import scrapy

class QiubaiproItem(scrapy.Item):
    # 語法:  欄位 = scrapy.Field()
    author = scrapy.Field()
    content = scrapy.Field()

setting中

  • 解開註釋
ITEM_PIPELINES = {
   'qiubaiPro.pipelines.QiubaiproPipeline': 300,  # 300優先順序
}

爬蟲檔案中

  • 必須匯入items 中的類
  • 將資料錄入item
  • 用yield item提交給管道
import scrapy
from qiubaiPro.items import QiubaiproItem


class QiubaiSpider(scrapy.Spider):
    name = 'qiubai'
    # allowed_domains = ['qiushibaike.com/text']  # 圖片可能不是該域名下
start_urls = ['https://www.qiushibaike.com/text/'] # https 要注意 def parse(self, response): # 取段子列表 div_list = response.xpath("//div[@id='content-left']/div") # 儲存解析到的頁面資料 data_list = [] for div in div_list: # xpath解析的內容儲存到 selector物件中,獲取內容.extract()
# extract_first()獲取內容 = .extract()[0] author = div.xpath("./div/a[2]/h2/text()").extract()[0] # 或extract_first() content = div.xpath(".//div[@class='content']/span/text()").extract_first() # 1.資料解析到items物件(先匯入) item = QiubaiproItem() item['author'] = author item['content'] = content # 2.將item物件提交給管道 yield item

管道pipelines中

  1. 現在資料庫中建立對應格式的表
  2. 匯入pymysql包
  3. 在open_spider中連結資料庫
  4. 利用pymysql進行資料錄入
  5. 用try捕獲並回滾錯誤
  6. 在close_spider中關閉資料庫
import pymysql


class QiubaiproPipeline(object):
    conn = None
    cursor = None  # 遊標物件

    # 1. 連結資料庫
    # 2. 執行sql語句
    # 3. 提交

    # 爬蟲開始執行
    def open_spider(self, spider):
        print('開始爬蟲,連結資料庫')
        self.conn = pymysql.Connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123',
            db='qiubai',
        )

    # 對提交的item物件,mysql資料庫儲存
    # 爬蟲每次提交item,該方法被執行一次
    def process_item(self, item, spider):

        # 寫sql語句 往qiubai這個表中插資料,沒有表的話要先在資料庫建立
        sql = 'insert into qiubai values("%s","%s")' % (item['author'], item['content'])

        # 建立遊標物件
        self.cursor = self.conn.cursor()

        # 提交事務
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            print(e)
            print('異常回滾')
            self.conn.rollback()

        return item

    # 結束爬蟲時呼叫
    def close_spider(self, spider):
        print('爬蟲結束')
        self.cursor.close()
        self.conn.close()