Excel VBA 簡易爬蟲

2022/01/05閱讀時間約 4 分鐘
首先用Chrome瀏覽器,在證交所的目標數據網頁上按F12,在Network、All、Headers項目下,逐一點選網頁的Name,然後搭配網頁選單的擾動,就能判斷正確的還原網址。以每5秒委託成交統計為例,還原的網址為
https://www.twse.com.tw/exchangeReport/MI_5MINS?response=json&date=20220105
有了網址後,就利用Excel VBA來做一隻簡單的網頁爬蟲

Option Explicit
Sub CatchWebData()
Dim urlText As String
Dim NumDate As String
Dim Path As String
NumDate = "20220105"
Path = "D:\" + NumDate + "證交所五秒數據.txt"
urlText = "https://www.twse.com.tw/exchangeReport/MI_5MINS?response=json&date="
urlText = urlText + NumDate
'台灣證券交易所,五秒委託、成交量,每日共計3241筆
'Part1 使用Late Binding方式,避免引用程序
Dim myXML As Object '宣告物件
Set myXML = CreateObject("Microsoft.XMLHTTP") '物件繼承XMLHTTP功能
'Part2 抓取資料
Dim myText As String
myXML.Open "GET", urlText, False '開啟目標網頁,開啟方法為GET
myXML.send '送出請求
myText = myXML.responseText '伺服器回傳資料,本機電腦用myText接收Set myXML = Nothing
'myText字串內容可以參考實際證交所網頁
'https://www.twse.com.tw/exchangeReport/MI_5MINS?response=json&date=20220105
'Part3 整理字串,JSON字串有固定格式{}、[]
Dim ii, x, y, z As Variant
x = InStr(1, myText, ":[[") + 3 '所需字串資料起點位置
y = InStr(1, myText, "]],") '所需字串資料末端位置
myText = Mid(myText, x, y - x) '重新抓取所需的字串資料,剃除頭尾不需要的資料
z = Split(myText, "],[") '利用拆字串函數,將分解後的集合,存入陣列之中
'Debug.Print z(0)
'Debug.Print z(3240)
Open Path For Append As #1 'Excel VBA 寫出到外部文字檔,使用Append、Print方法
Print #1, "時間;委買筆;委買量;委賣筆;委賣量;成交筆;成交量;成交金額"
Close #1
For ii = 0 To 3240
z(ii) = Replace(z(ii), Chr(34) & "," & Chr(34), ";") '整理資料:將資料間的逗號改為分號
z(ii) = Replace(z(ii), Chr(34), "") '整理資料:去除資料間的引號
Open Path For Append As #1
Print #1, z(ii)
Close #1
Next ii
End Sub
為什麼會看到廣告
    Piemann
    Piemann
    Piemann 只是一位中年大叔 !
    留言0
    查看全部
    發表第一個留言支持創作者!