2016年3月16日 星期三

Excel VBA 抓元大網頁EFT的表格

好久沒寫關於用Excel VBA抓網頁資料,剛好群裡有朋友問到 元大ETF網頁的內容要如何抓取,小試了一下順道做紀錄。
這個網頁有一個特色就是它會在網頁按下同意按鈕後,在瀏覽器寫進一個cookie,如果沒有注意到,這樣一個特性,真的很不好抓出表格,大家可以多練習,參考以下原始碼。
Sub 抓元大ETF網頁()

    Dim IE As Object, doc As Object, element As Object
    
    Const url As String = "http://www.yuantaetfs.com/#/RtNav/Index"
    
    With CreateObject("internetexplorer.application")
        .Visible = False
        .Navigate url
        
        Do While .Busy Or .ReadyState <> 4
            DoEvents
        Loop
        Do
            DoEvents
        Loop Until .Document.ReadyState = "complete"

        '.Document.cookie = "IsAgreeRtNav=TRUE"
        
        Set doc = .Document
        Set element = doc.getElementsByTagName("table")(22)
        With ActiveSheet
            For i = 0 To element.Rows.Length - 1
                For j = 0 To element.Rows(i).Cells.Length - 1
                    .Cells(i + 1, j + 1) = element.Rows(i).Cells(j).innerText
                Next
            Next
        End With
        .Quit
    End With
    
    Set doc = Nothing
    Set element = Nothing
    Set IE = Nothing
End Sub