【问题标题】:Click button without ID using VBA使用VBA单击没有ID的按钮
【发布时间】:2020-07-14 04:13:35
【问题描述】:

我想使用 VBA 从 NASDAQ 下载历史数据。我已经设法将“FromDate”更改为正确的范围,但我没有设法让代码点击提取数据的“搜索”按钮(因为它没有 ID)。请帮帮我。

我的 VBA:

Sub OMX_data()

Dim URL As String
Dim ie As InternetExplorer

Set ie = New InternetExplorer
ie.Visible = True

ie.navigate ("http://www.nasdaqomxnordic.com/indexes/historical_prices?Instrument=DK0060368991")

Do
DoEvents
Loop Until ie.readyState = 4

ie.document.all("FromDate").Value = "2018-01-01"

End Sub

HTML

<div class="filterAreaRow overflowHidden">
<div class="button doSearch floatRight ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" onclick="historical.load();return false;" role="button" aria-disabled="false"><span class="ui-button-text">Search</span></div>
</div>

【问题讨论】:

    标签: html vba web-scraping automation onclick


    【解决方案1】:

    您可以使用getElementsByClassName按类获取搜索按钮元素,并可以通过Click方法触发,doSearch是该表单中搜索按钮的名称。

    最后两行是你的问题的解决方案。

    Sub OMX_data()
        Dim URL As String
        Dim ie As InternetExplorer
    
        Set ie = New InternetExplorer
        ie.Visible = True
    
        ie.navigate ("http://www.nasdaqomxnordic.com/indexes/historical_prices?Instrument=DK0060368991")
    
        Do
            DoEvents
        Loop Until ie.readyState = 4
    
        ie.Document.all("FromDate").Value = "2018-01-01"
    
        Set search_button = ie.Document.getElementsByClassName("doSearch")
        search_button(0).Click
    End Sub
    

    您可以使用 HTML DOM 将数据导入 Excel, 下面是导入数据到 Excel 的示例

    Sub OMX_data()
        Dim URL As String
        Dim ie As InternetExplorer
    
        Set ie = New InternetExplorer
        ie.Visible = True
    
        ie.Navigate ("http://www.nasdaqomxnordic.com/indexes/historical_prices?Instrument=DK0060368991")
    
        Do
            DoEvents
        Loop Until ie.ReadyState = 4
    
        ie.Document.all("FromDate").Value = "2018-01-01"
    
        Set search_button = ie.Document.getElementsByClassName("doSearch")
        search_button(0).Click
    
        ' Wait for filter apply
        Application.Wait (Now + TimeValue("0:00:05"))
    
        ' Use HTML DOM
        Set result = ie.Document.getElementById("historicalOutput").getElementsByTagName("tbody")(0).getElementsByTagName("tr")
    
        i = 0   ' for row
        For Each r In result
            j = 0   ' for column
            For Each c In r.Children
                Range("A1").Offset(i, j).Value = c.innertext
                j = j + 1
                DoEvents
            Next
            i = i + 1
        Next
    
        MsgBox "Import finish"
    End Sub
    

    【讨论】:

    • 太棒了!有用。您是否也可以帮助我将数据变得优秀,或者应该是另一个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2020-04-11
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多