Excel VBA& IE 11 - 在下拉列表中选择值后无法刷新页面

时间:2016-10-03 08:35:37

标签: excel vba internet-explorer web-scraping

我正试图获得WorldRemit为一对货币提供的货币汇率。我想更改网页左上角“发送自”下拉列表中的值。 (https://www.worldremit.com/en/South-Africa

我无法使用.Selected = True.Click选择下拉选项,因此使用了.SelectedIndex。选择值后,我无法触发刷新页面的更改事件。如果有人可以帮我解决这个问题会很棒。

导航到页面的代码:

Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate "https://www.worldremit.com/en/South-Africa"
While ie.busy
  DoEvents
Wend
Set HTMLdoc = ie.document

使用.SelectedIndex属性选择选项的代码:

Dim fromSelect As HTMLSelectElement
Set fromSelect = HTMLdoc.getElementById("selectFrom")
optionIndex = Find_Select_Option(fromSelect, "Germany")
If optionIndex >= 0 Then
    fromSelect.selectedIndex = optionIndex
    fromSelect.FireEvent ("onchange") ' this doesn't work
End If

选择选项的功能(在上面的代码中使用):

Function Find_Select_Option(selectElement As HTMLSelectElement, optionText As String) As Integer

Dim i As Integer 
Find_Select_Option = -1
i = 0
While i < selectElement.Options.Length And Find_Select_Option = -1
    DoEvents
    If LCase(Trim(selectElement.Item(i).Text)) = LCase(Trim(optionText)) Then Find_Select_Option = i
    i = i + 1
Wend    
End Function

编辑#1:包含相关元素的HTML代码段是

<select id="selectFrom" data-track-field-name="from country" data-track-event="change">...</select>

2 个答案:

答案 0 :(得分:0)

试一试,它正在我的工作。有时使用jQuery会更容易一些,尤其是当页面也使用jQuery时。

您可以使用IE的execScript函数来使用jQuery。见下文:

 Public Sub test()
    Dim IE As Object: Set IE = CreateObject("InternetExplorer.Application")

    With IE
        .Visible = True
        .navigate "https://www.worldremit.com/en/South-Africa"
        'Wait for the page to load
        While .busy Or .readyState <> 4
            Application.Wait (Now() + TimeValue("00:00:01"))
            DoEvents
        Wend
        'Use JQuery to find the element based on ID, then make the Selected property true
        'Once that is done, call the change event in jQuery
        .document.parentWindow.execScript "$('#selectFrom option:contains(Germany)').prop('selected','True')"
        .document.parentWindow.execScript "$('#selectFrom option:contains(Germany)').change()"
    End With
End Sub

答案 1 :(得分:0)

显然FireEvent对IE 11的效果不佳,因此需要使用CreatEvent + initEvent + dispatchEvent

下面的工作代码段:

Dim fromSelect As HTMLSelectElement
Dim evt As Object

Set evt = HTMLdoc.createEvent("HTMLEvents")
evt.initEvent "change", True, False
Set fromSelect = HTMLdoc.getElementById("selectFrom")
optionIndex = Find_Select_Option(fromSelect, "Germany")
If optionIndex >= 0 Then
    fromSelect.selectedIndex = optionIndex
    fromSelect.dispatchEvent evt
End If