加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何使用selenium java从多选下拉列表中显示所选选项?

发布时间:2020-12-15 04:38:07 所属栏目:Java 来源:网络整理
导读:我正在尝试从多选下拉列表中显示所有选定的选项.但没有得到正确的方法来做到这一点.请帮帮我. 这是下拉列表的html代码: select multiple id="fruits" option value="banana"Banana/option option value="apple"Apple/option option value="orange"Orange/op
我正在尝试从多选下拉列表中显示所有选定的选项.但没有得到正确的方法来做到这一点.请帮帮我.

这是下拉列表的html代码:

<select multiple id="fruits">
     <option value="banana">Banana</option>
     <option value="apple">Apple</option>
     <option value="orange">Orange</option>
     <option value="grape">Grape</option>
</select>

这是我正在尝试的代码:

public void dropDownOperations()
    {
        driver.get("http://output.jsbin.com/osebed/2");
        Select DDLIST = new Select(driver.findElement(By.id("fruits")));
        DDLIST.selectByIndex(0);
        String currentvalue = DDLIST.getFirstSelectedOption().getText();
        System.out.println(currentvalue);
        DDLIST.selectByIndex(1);
        String currentvalue1 = DDLIST.getFirstSelectedOption().getText();
        System.out.println(currentvalue1);          
    }

我也尝试过这段代码:

在这里我得到这个输出:

[[[[[ChromeDriver: chrome on XP (69aee19e9922ca218ff47c0ccdf1bbbc)] ->
id: fruits]] -> tag name: option],[[[[ChromeDriver: chrome on XP
(69aee19e9922ca218ff47c0ccdf1bbbc)] -> id: fruits]] -> tag name:
option]]

public void dropDownOperations1()
    {
        driver.get("http://output.jsbin.com/osebed/2");
        Select DDLIST = new Select(driver.findElement(By.id("fruits")));
        DDLIST.selectByIndex(0);
        DDLIST.selectByIndex(1);
        List<WebElement> currentvalue1 = DDLIST.getAllSelectedOptions();
        System.out.println(currentvalue1);          
    }

解决方法

您的第二种方法应该可以正常使用一个小修复. getAllSelectedOptions()将返回选定选项的列表作为WebElement.您需要遍历列表以从WebElement获取文本.

List<WebElement> selectedOptions = DDLIST.getAllSelectedOptions();
for (WebElement option : selectedOptions){
        System.out.println(option.getText());
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读