excel 用VBA选择HTML下拉菜单

jm2pwxwz  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(135)

我试图刮一个下拉式的网站,预设为20,选项20,50和100。
我试图选择100,但是设置. value ="100"导致错误;.单击"打开"下拉菜单,以便所有选项变为可见;而. selectedIndex = x似乎没有任何作用。有没有其他方法可以将下拉菜单设置为"100"或单击下拉菜单并选择"100"?
HTML:

<span class="k-dropdown-wrap k-state-default k-state-active k-state-border-down" unselectable="on">
<span class="k-input" unselectable="on">20</span>
<span class="k-select" aria-label="select" unselectable="on">
<span class="k-icon k-i-arrow-60-down"></span></span></span>
<select style="display: none;" aria-label="20" data-role="dropdownlist">
    <option selected="selected" value="20">20</option>
    <option value="50">50</option>
    <option value="100">100</option>
</select>

我的VBA:

If Not ieWebsite.document.getElementsByClassname("k-widget k-dropdown") Is Nothing Then
    Dim perPageOptions As Long
    perPageOptions = ieWebsite.document.getElementsByClassname("k-widget k-dropdown").Length
    For i = 0 To perPageOptions - 1
        On Error Resume Next
        For x = 0 To ieWebsite.document.getElementsByClassname("k-widget k-dropdown")(i).getElementsByTagName("option").Length - 1
            If ieWebsite.document.getElementsByClassname("k-widget k-dropdown")(i).getElementsByTagName("option")(x).Value = "100" Then
                ieWebsite.document.getElementsByClassname("k-widget k-dropdown")(i).getElementsByTagName("option")(x).Click 'JUST CLICKS THE DROPDOWN, NOT THE ACTUAL "100"
                Exit For
            End If
        Next x
        If Err.Number <> 0 Then
            Err.Clear
        Else
            Exit For
        End If
    Next i
End If
qvtsj1bj

qvtsj1bj1#

以下是更改其值的方法:

Dim selectList As Object
Set selectList = ieWebsite.document.querySelector("select[aria-label=""20""][data-role=""dropdownlist""]")

If Not selectList Is Nothing Then
    Dim i As Long
    For i = 0 To selectList.Options.Length - 1
        If selectList.Options(i).Value = "50" Then
            selectList.selectedIndex = i
            Exit For
        End If
    Next i
End If

我敢肯定,你必须使列表可见之前,你可以点击该选项:

Dim selectList As Object
Set selectList = ie.document.querySelector("select[aria-label=""20""][data-role=""dropdownlist""]")

If Not selectList Is Nothing Then
    selectList.Style.display = "inline-block"
    
    Dim i As Long
    For i = 0 To selectList.Options.Length - 1
        If selectList.Options(i).Value = "50" Then
            selectList.Options(i).Click
            Exit For
        End If
    Next i
End If

相关问题