我将此代码与Java和Selenium一起用于选择复选框。
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:
更自然的方式是:
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
方法将自动返回定位的元素,这样就不需要额外的代码。
您可以简单地添加wait,直到元素可点击为止
像这样:
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();