添加等待复选框 select

Add wait to checkbox select

我将此代码与 Java 和 Selenium 一起用于 select 复选框。

WebElement element = driver.findElement(By.id(inputId));
System.out.println("Selecting checkbox value " + value + " using id locator " + inputId);
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

是否可以添加等待侦听器以使复选按钮可点击?有时代码会因异常而失败:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:

您可以简单地添加等到元素可点击。
像这样:

public void waitForElementToBeClickable(By element) {
    wait.until(ExpectedConditions.elementToBeClickable(element));
}

然后:

waitForElementToBeClickable(By.id(inputId));
WebElement element = driver.findElement(By.id(inputId));
System.out.println("Selecting checkbox value " + value + " using id locator " + inputId);
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

更自然的方式是:

Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(inputId)));
System.out.println("Selecting checkbox value " + value + " using id locator " + inputId);
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

until方法会自动return定位元素,所以不需要额外的代码。