如果您只需要等待页面加载,您可以执行 Javascript 函数来检查页面加载是否完成:
String val = "";
do {
val = (String)((JavascriptExecutor)driver).executeScript("return document.readyState");
// DO WHATEVER
} while (!"complete".equals(val));
使用时,findElement()
您必须在尝试定位元素之前使用隐式等待。否则,NoSuchElementException
如果页面上没有加载组件,可能会抛出:
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // Blocks NoSuchElementExceptions for 5 seconds when findElement() is called (set for the duration of driver's life.
WebElement element = driver.findElement(By.xpath("//div[contains(text(),'Loading...')]"));
应该明智地使用该策略,因为它很可能会影响测试的性能。或者,您应该使用WebDriverWait
(显式等待):
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Loading...')]"))); // Presence of component checks the existence of the element in the DOM which it will always be true
System.out.println("Testing visibility passed...");
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[contains(text(),'Loading...')]"))); // Presence of component checks the existence of the element in the DOM which it will always be true
System.out.println("Testing invisibility passed...");
请注意,在最后一个策略中,visibilityOfElementLocated
返回 aWebElement
并visibilityOfElementLocated
返回 a Boolean
。因此,您不能使用.andThen(Function)
.