使用scrapy抓取ptt批踢踢Gossiping版資料儲存到Mysql

使用Scrapy使用抓取ptt批踢踢Gossiping版( https://www.ptt.cc/bbs/Gossiping/index.html)的資料儲存到Mysql資料庫。

Step0)建立資料庫ptt,新增資料表page,資料表page的SQL如下。

Step1)使用「scrapy startproject ptt」建立ptt專案,「cd ptt」切換到ptt資料夾,使用「scrapy genspider page ptt.cc」建立spider/page.py

Step2)編輯ptt\scrapy\page.py,如下,scrapy使用start_urls的網址抓取資料,自動呼叫函式parse,將資料儲存到item物件,scrapy經由設定會將item交給pipeline處理,在pipeline撰寫程式將資料加到Mysql資料庫。

Step3)修改ptt\item.py,建立資料接收的資料欄位

Step4)修改ptt\pipelines.py,將item插入到資料庫

Step5)本專案設定檔在ptt\settings.py,新增資料庫設定,啟用ITEM_PIPELINES才會將item儲存到Mysql資料庫

Step6)在ptt資料夾執行指令「scrapy crawl page」就可以抓取抓取ptt批踢踢Gossiping版資料,儲存到Mysql資料庫ptt的資料表page中,使用phpmyadmin瀏覽結果如下圖。