我在页面上有一个Web元素按定位器的枚举列表。我希望能够使用枚举以及我希望选择的选项的值的附加信息的组合来选择选择框的特定选项。有什么办法吗?我注意到By类也具有findElement(searchContext)方法。我可以将其用作类似于以下内容的东西吗?

public enum Dictionary {

    TYPE                        (By.id("vehType")),
    PROVINCE                    (By.id("provId")),
    TERRITORY                   (By.id("territoryId")),
    STAT_CODE                   (By.id("statCodeId")),
    CLASS                       (By.id("class1Id"));

    private final By locator;

    private DetailVehicleDictionary (By value) {
        this.locator = value;
    }

    public By getLocation() {
        return this.locator;
    }
}

然后,如果CLASS是HTML的选择框,则:
<select id="class1Id" name="select_box">
    <option value="1"/>
    <option value="2"/>
    <option value="3"/>
</select>

我可以按照以下方式做点什么:
WebElement specificValue = driver.findElement(Dictionary.CLASS.getLocation().findElement(By.cssSelector("option[value=2]"));

我需要访问实际元素,以便我可以等待该值出现在DOM中。我计划在一个等待命令中实现这一点,例如:
wait.until(ExpectedConditions.presenceOfElementLocated(specificValue));

最佳答案

Selenium有一个special mechanism来处理“选择/选项”情况:

import org.openqa.selenium.support.ui.Select;  // this is how to import it

WebElement select = driver.findElement(Dictionary.CLASS.getLocation());
Select dropDown = new Select(select);
dropDown.selectByValue("1");

后续问题的答案:使用Explicit Wait:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement select = wait.until(ExpectedConditions.presenceOfElement(Dictionary.CLASS.getLocation()));

恐怕在等待将选项加载到select中的情况下,您可能需要制作一个自定义的ExpectedCondition(未经测试):
public static ExpectedCondition<Boolean> selectContainsOption(
    final WebElement select, final By locator) {

    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            try {
                return elementIfVisible(select.findElement(locator));
            } catch (StaleElementReferenceException e) {
                return null;
            }
        }
    };
}

用法:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement select = wait.until(ExpectedConditions.presenceOfElement(Dictionary.CLASS.getLocation()));
WebElement option = wait.until(selectContainsOption(select, By.cssSelector('.//option[@value = "1"]')));

10-06 03:46