【问题标题】:Selenium/Java: get index/position of currently selected option in a dropdown menuSelenium/Java:获取下拉菜单中当前选定选项的索引/位置
【发布时间】:2014-11-14 10:09:20
【问题描述】:

如何在 Selenium 的下拉菜单中获取当前选定选项的索引?获取文本标签很容易

String searchString = select.getFirstSelectedOption().getText();

选择第n个元素也很容易

select.selectByIndex(25);

但我想知道当前选中项的索引是25。当我知道我要记录该值,然后按索引选择下一个。

【问题讨论】:

    标签: java select selenium indexing html.dropdownlistfor


    【解决方案1】:

    我使用了下拉列表的以下html代码sn-p:-

    <select name="Students">
    <option value="student1">student1</option>
    <option value="student2">student2</option>
    <option value="student3">student3</option>
    <option value="student4">student4</option>
    </select>
    

    以下是从下拉列表中选择然后获取所选选项的索引的代码:-

        Select sel = new Select(driver.findElement(By.xpath("//select[@name='Students']")));
    
        sel.selectByVisibleText("student4");
    
        List<WebElement> list = sel.getOptions();
    
        for(int i=0;i<list.size();i++){
            if(list.get(i).getText().equals(sel.getFirstSelectedOption().getText())){
                System.out.println("The index of the selected option is: "+i);
                break;
                }
        }
    

    注意:-输出将是“3”,因为索引从“0”开始。

    【讨论】:

      【解决方案2】:

      在我们的 Selenium-Tests 中,使用了更简洁的 sn-p:

      int index = select.getOptions().indexOf(select.getFirstSelectedOption();
      

      【讨论】:

        猜你喜欢
        • 2021-04-02
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多