我会给你一些我如何实现等待的例子,也许它会帮助你更灵活。
我创建了一个带有默认时间的时间参数的基本 waitUntil 方法。
private void waitUntil(ExpectedCondition<WebElement> condition, Integer timeout) {
timeout = timeout != null ? timeout : 5;
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(condition);
}
然后我可以使用该辅助方法来创建等待显示或等待可点击。
public Boolean waitForIsDisplayed(By locator, Integer... timeout) {
try {
waitUntil(ExpectedConditions.visibilityOfElementLocated(locator),
(timeout.length > 0 ? timeout[0] : null));
} catch (org.openqa.selenium.TimeoutException exception) {
return false;
}
return true;
}
您可以对 elementToBeClickable 进行类似操作。
public Boolean waitForIsClickable(By locator, Integer... timeout) {
try {
waitUntil(ExpectedConditions.elementToBeClickable(locator),
(timeout.length > 0 ? timeout[0] : null));
} catch (org.openqa.selenium.TimeoutException exception) {
return false;
}
return true;
}
所以我们可以创建一个点击方法来执行我们的点击来使用它:
public void click(By locator) {
waitForIsClickable(locator);
driver.findElement(locator).click();
}
我制作 waitForIsDisplayed 和 waitForIsClickable 的原因是因为我可以在我的断言中重用它们以减少它们的脆弱性。
assertTrue("Expected something to be found, but that something did not appear",
waitForIsDisplayed(locator));
另外,您可以使用方法中指定的默认时间(5 秒)的等待方法,或者可以这样做:
waitForIsDisplayed(locator, 20);
在抛出异常之前最多等待 20 秒。