《SeleniumBasic 3.141.0.0

<html>
 <body>
        <div>你去过那些地方?</div>
        <br />
        <select name="调查" multiple="multiple" size="8">
            <option value="河南省">河南省</option>
            <option value="湖北省">湖北省</option>
            <option value="黑龙江省">黑龙江省</option>
            <option value="江西省">江西省</option>
            <option value="新疆">新疆</option>
            <option value="内蒙古">内蒙古</option>
            <option value="西藏">西藏</option>
        </select>
    </body>
</html>

 如果一个网页中有多选列表框,特征是multiple="multiple",可以按住Ctrl或Shift选择多选。

你去过那些地方?

 SeleniumBasic中,有一些以Select和DeSelect开头的方法,用于操作多选下拉框。

  1. Sub SelectByIndex(index As Long)
  2. Sub SelectByText(Text As String, [partialMatch As Boolean = False])
  3. Sub SelectByValue(Value As String)
  4. Sub DeselectAll()
  5. Sub DeselectByIndex(index As Long)
  6. Sub DeselectByText(Text As String)
  7. Sub DeselectByValue(Value As String)

其中De开头的是反选,也就是取消选中。例如DeSelectAll可以全部不选。

但是Selenium没有全选的方法,如果要选择所有,需要在循环中单独选中每一个。实例如下:

    Dim sel As SeleniumBasic.IWebElement
    Set sel = WD.FindElementByName("调查")
    Dim items() As SeleniumBasic.IWebElement
    items = sel.FindElementsByTagName("option")
    If sel.IsMultiple Then
        For i = 0 To UBound(items)
            sel.SelectByIndex i
        Next i
    End If
    If sel.IsMultiple Then
        sel.DeselectByText "江西省"
        sel.DeselectAll
    End If

程序中的For循环执行完后,列表框所有的项目都被选中了。 

另外,SeleniumBasic提供了下拉列表框中遍历每个option的方法。

  • Options:返回下拉列表框中所有option项
  • AllSelectedOptions:返回处于选中状态的所有option项
  • SelectedOption:返回选中的那一个option项

假设有3个被选中了,然后运行如下程序,打印出所有条目。

Dim Col() As IWebElement
Col = sel.Options
For i = 0 To UBound(Col)
Debug.Print Col(i).text
Next i

河南省
湖北省
黑龙江省
江西省
新疆
内蒙古
西藏

再运行如下程序,打印出处于选中的条目。

Col =sel.AllSelectedOptions
For i = 0 To UBound(Col)
Debug.Print Col(i).text
Next i

湖北省
江西省
西藏

最后运行 Debug.Print sel.SelectedOption.text

打印出:湖北省

原文地址:https://www.cnblogs.com/ryueifu-VBA/p/13695331.html