如何使用内部文本从网页的下拉列表中选择选项

时间:2019-05-29 05:14:35

标签: html excel vba excel-vba

如何使用内部文本从网页的下拉列表中选择一个选项

下面是vba代码

Sub navigation_site_with_part_number()
    Dim eRow As Long
    Dim ele As Object
    Set sht = Sheets("Sheet1")
    RowCount = 1`enter code here
    eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    Set objIE = CreateObject("InternetExplorer.Application")
    requestnumber = InputBox("Enter the request number.")
    With objIE
    .Visible = True
    .navigate "*http://www.auto.com*"
    Do While .Busy Or _
    .readyState <> 4
    DoEvents
    Loop
    .document.getElementsByid("inspNumber").selectedinnertext = 2
   .document.getElementById("InspQuery_Search").Click
    Do While .Busy Or _
   .readyState <> 4
    DoEvents
    Loop
    End With

以下是HTML代码:

div id="RequestNumberGroup" class="form-group">
<label for="TextRequestNumber">Request Number:</label>
<select class="form-control" id="inspNumber" name="inspNumber">
  <option value=""></option>
  <option value="813">20190205</option>
  <option value="1034">20190426</option>
  <option value="1059">20190451</option>
  <option value="1061">20190453</option>
  <option value="1064">20190456</option>
  <option value="1065">20190457</option>

我希望在下拉列表中选择请求号而不是选项值的选项

1 个答案:

答案 0 :(得分:0)

在IE实施中没有按文本选择选项。

1)要么收集选项的集合/节点列表,然后将innerText与所需的文本字符串进行比较,然后选择是否找到并退出

Dim options As Object, i As Long, found As Boolean

Set options = ie.document.querySelectorAll("#inspNumber options")

For i = 0 To options.length - 1
    If options.item(i).innerText = "target string" Then
        options.item(i).Selected = True
        found = True
        Exit For
    End If
Next
If Not found Then
    'do something if not found
End If

2)使用确实实现此功能的selenium vba wrapper

Dim ele As Select
Set ele = driver.FindElementById("inspNumber").AsSelect
ele.SelectByText "Option Text"

当然,可以使用属性值和selectedIndex方法,但是您不想要这些。