selenium自动化提供三种等待方式:
1.强制等待(sleep)
让程序暂停运行一定时间,时间过后继续运行。
Thread.sleep(millis);
2.隐式等待(implicitly_wait())
当使用了隐式等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常, 换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM。
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
3. 显式等待 (WebDriverWait)
指定一个等待条件,和一个最长等待时间,程序会判断在等待时间内条件是否满足,如果满足则返回,如果不满足会继续等待,超过时间就会抛出异常。显式等待过程中需忽略NoSuchElementException等报错。
/**
* 等待直到某元素的出现
*/
public static boolean waitForElementPresent(int timeout, By locator) {
boolean isPresent = false;
try {
new WebDriverWait(driver, timeout)
.ignoring(StaleElementReferenceException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOfElementLocated(locator));
isPresent = true;
} catch (Exception e) {
isPresent = false;
}
return isPresent;
}
/**
* 等待直到某元素的出现
*/
public static boolean waitForElementPresent(int timeout, WebElement element) {
boolean isPresent = false;
try {
new WebDriverWait(driver, timeout)
.ignoring(StaleElementReferenceException.class, NoSuchElementException.class)
.until(ExpectedConditions.visibilityOf(element));
isPresent = true;
} catch (Exception e) {
isPresent = false;
}
return isPresent;
}
实际应用中多采用隐式等待和显式等待结合的方法,在启动driver后设置一个全局的隐式等待,在具体的方法中结合具体的元素使用显式等待。