Excel VBA IE自动化-无法单击已经正确聚焦的按钮

时间:2019-08-23 21:43:15

标签: html vba internet-explorer web-scraping

我使用宏打开使用IE的页面,在搜索框中输入一个值,然后单击“执行”按钮。我可以成功地将焦点放在“转到”按钮上,但是单击不起作用。

目标是打开新页面,然后获取指向该页面的链接。 (... BondCenter / BondDetail.jsp?ticker = C77821&symbol = ZUAN.GA)

    '''Function to search a value and click GO button

    URL = "http://finra-markets.morningstar.com/MarketData/Default.jsp?sdkVersion=2.37.0"

    Set IE = CreateObject("InternetExplorer.Application")

    IE.Visible = True
    IE.Navigate URL

    WaitFor IE
    Application.Wait Now + TimeSerial(0, 0, 3)

    IE.document.getElementById("ms-finra-autocomplete-box").Value = "ZUAN.GA"

    Application.Wait Now + TimeSerial(0, 0, 1)

    Max = 25
    For j = 0 To Max
         If IE.document.getElementsByTagName("input").Item(j).getAttribute("type") = "submit" Then
            If IE.document.getElementsByTagName("input").Item(j).getAttribute("value") = "GO" Then
               Set Button = IE.document.getElementsByTagName("input").Item(j)

                  'The GO button gets successfully focused
                  Button.Focus

                  'Method#1 below does not click on the Button successfully
                  Button.FireEvent ("onchange")

                  'Method#2 below does not click on the Button
                  Button.FireEvent ("onclick")

                  'Method#3 below does not click on the Button
                  Button.Click

                  Exit For
             End If
         End If
      Next

    ''' Function to wait for IE
    Sub WaitFor(IE As Object)
        While IE.readyState <> 4
            DoEvents
        Wend
    End Sub

1 个答案:

答案 0 :(得分:0)

如果您检查html,则会发现mousedown按钮上有一个Go的事件侦听器。如果创建并触发该事件,则将获得预期的结果。

事件侦听器示例:

enter image description here


Option Explicit
Public Sub test()
    Dim ie As InternetExplorer, url As String, evt As Object

    url = "http://finra-markets.morningstar.com/MarketData/Default.jsp?sdkVersion=2.37.0"
    Set ie = New InternetExplorer

    With ie
        .Visible = True
        .Navigate2 url
        While .Busy Or .readyState <> 4: DoEvents: Wend

        With .document
            .querySelector("#ms-finra-autocomplete-box").Value = "ZUAN.GA"
            Set evt = .createEvent("HTMLEvents")
            evt.initEvent "mousedown", True, False   
            .querySelector("[value=GO]").dispatchEvent evt
        End With

        Do While .document.url = url: DoEvents: Loop

        MsgBox .document.url
    End With
End Sub