Python爬蟲:爬取牌告匯率及匯到資料庫

運用pandas修改欄位再匯成資料庫

MinKuan
4 min readAug 10, 2020

前言

今天將會分享如何使用python爬取台灣銀行的黃金牌告價格並畫出線圖。

在開始爬蟲時都要先研究 目標是誰?結構是甚麼?我要什麼資料?希望最後的資料長怎麼樣? 在腦中有些許畫面後,我們就可以開始了!!!

將學習到

· 使用pandas爬取台灣銀行牌告匯率的表格、整理資料

· 使用sqlite3連結資料庫

環境設定

win10 Anaconda的jupyter(6.0.3)

使用套件

import pandas

from datetime import datetime

import sqlite3

開始工作

步驟1:檢查目標

可以先點開該網站並按滑鼠右鍵”檢查”,先快速看過此網站結構。

https://rate.bot.com.tw/xrt?Lang=zh-TW

步驟2:使用pandas爬取網站並整理

#爬取網站
import pandas as pd
url=”https://rate.bot.com.tw/xrt?Lang=zh-TW"
res = pd.read_html(url)
#獲得表格
df = res[0]
#全部的row(行)以及0~5的index(列)
currency=df.iloc[:,:5]
#自訂欄位名稱
currency.columns=[u”幣別”,u”現金匯率-本行買入”,u”現金匯率-本行賣出”,u”即期匯率-本行買入”,u”即期匯率-本行賣出”]
#修正’幣別’欄位
currency[u’幣別’]=currency[u’幣別’].str.extract(‘\((\w+)\)’)
初步整理
#匯入時間
from datetime import datetime
currency["date"]=datetime.now().strftime("%Y-%m-%d")
#將index改為時間
currency.index=currency['date']
currency.head()
加入時間後

加入時間是為了方便辨別,同時也可以利用這個方法去繪製折線圖。

步驟3:使用sqlite3將資料匯入資料庫

import sqlite3
#連結資料庫檔or創建資料庫檔
conn = sqlite3.connect(‘currency.db’)
#資料庫游標
c = conn.cursor()
#創建資料庫
c.execute(“DROP TABLE IF EXISTS currency ;”)
#將資料匯入
currency.to_sql(name=’currency’, con=conn, if_exists=’replace’, index=False)
#執行
conn.commit()
#關閉資料庫
conn.close()

這邊用to_sql將整理好的currency資料匯成.db檔,如果想變成.csv或,xlsx可用to_csvto_excel,而資料將會在的anaconda的資料夾裡,預設的話可以在//user裡找到 。

conn.cursor()游標是使用資料庫時大家的習慣用法,沒有特別的意思。

成果展示

上圖是用SQLite開啟currency.db

完整程式碼

小結

這邊練習到pandas的簡單整理方法,也學到如何將整理好的資料匯成資料庫,如果你對於以上的內容有建議歡迎提出,一起討論絕對是成長的捷徑!!

參考資料

[爬蟲實戰] 如何撰寫Python爬蟲抓取台灣銀行的牌告匯率?
[爬蟲實戰] 如何使用Pandas 函式將台灣銀行的牌告匯率存進資料庫中?

--

--

MinKuan
MinKuan

No responses yet