根据我看到的一些文章,使用Thread.sleep()似乎是不受欢迎的。在我的测试类中,我经常使用它来等待某些内容加载完成。我曾试图使用这种方法来告诉我何时加载完成,但没有帮助。它不是一种可靠的方法。
try {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
|| ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
} catch (Exception e) {
System.err.println(thisClass + " Exception caught: " + e.getMessage());
}
我可以使用哪些替代方法?
这个解决方案有效:
Calling function:
String className = "gwt-Button form-control btn back-button ripple-container"; String textToFind = "back-button-icon"; String htmlElement = "button"; boolean isReady = Common.FluentWait(driver, 60, className, textToFind, htmlElement);
That function:
public static boolean FluentWait(WebDriver driver, int timeOut, String className, String textToFind, String htmlElement) { // Waiting timeOut seconds for an element to be present on the page, checking // for its presence once every 5 seconds. Common.myPrint(thisClass + " FluentWait. "); Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(timeOut, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { Common.myPrint(thisClass + " run returnWebElement. "); return returnWebElement(className, textToFind, htmlElement, driver); } }); if (foo != null) { return true; } return false;
}
我调用的函数是:
public static WebElement returnWebElement(String className, String textToFind, String htmlElement,
WebDriver driver) {
List<WebElement> elements = Common.findElementsUsingHtmlXpathClass(driver, htmlElement, className);
Common.myPrint(thisClass + " elements count: " + elements.size());
String text = "";
for (WebElement element : elements) {
// select an element
if (element.isDisplayed()) {
text = element.getAttribute("innerHTML");
if (text != "") {
text = text.trim();
if (text.contains(textToFind)) {
Common.myPrint(thisClass + " innerHTML: " + text);
Common.myPrint(thisClass + " returning element found. ");
return element;
}
}
}
}
Common.myPrint(thisClass + " element not found. ");
return null;
}
.withTimeout(30, SECONDS)
,并且这是pollingEvery(5, SECONDS)
的间隔,每5秒钟它将检查一次。 - RoushanFluentWait
。WebDriverWait
完全可以胜任。只有当您需要自定义等待的所有方面时,才需要使用FluentWait
,而大多数人只需要等待X秒钟以使某些条件为真,例如等待元素可点击,可见等。 - JeffC