使用elementToBeSelected / elementSelectionStateToBe选择是否选中检查下拉选项。

时间:2016-02-06 15:59:02

标签: selenium selenium-webdriver

我想检查是否选择了下拉列表中的选项。 Webdriver应该等到选择了值,然后执行下一个操作。我试图使用elementToBeSelected / elementSelectionStateToBe,但我无法做到。怎么用呢?

2 个答案:

答案 0 :(得分:1)

使用WebDriverWaitExpectedCondition“elementToBeSelected”应该做你想要的(它调用带有参数true的elementSelectionStateToBe)。 如果它不适合您,请检查传递参数是否确实是您要选择的WebElement选项。

代码如下所示:

WebElement option = driver.findElement(By.xpath("path/to/your/option[2]"));
new WebDriverWait(driver, 10)
    .until(ExpectedConditions.elementToBeSelected(option));

另一个选择是使用匿名类创建自己的条件,例如可以是值的相等。

final Select select = new Select(driver.findElement(By.xpath("path/to/your/select"));
new WebDriverWait(driver, 10)
        .until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                // this will get actual selected option and compare its value with expected value
                return select.getFirstSelectedOption().getAttribute("value").equals(expectedValue);
            }
        });

答案 1 :(得分:0)

尝试

    WebElement searchDDwn = driver.findElement(By.xpath(".//*[@id='edit-source']"));
    Select dropdown= new Select(searchDDwn);
    dropdown.selectByValue("Website");
    WebElement selected = dropdown.getFirstSelectedOption();

    boolean elementToBeSelected = wait.until(ExpectedConditions.elementToBeSelected(selected));
    System.out.println("elementToBeSelected results"+elementToBeSelected);