方法1:限定时间内等待元素,超时则抛出异常
public WebElement waitfor(final By by, int timeout) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(driver, timeout);
try {
element = wait.until((new Function<WebDriver, WebElement>() { //util 方法 判断特定条件是否存在
public WebElement apply(WebDriver webDriver) { //目标元素查找
WebElement wElement = webDriver.findElement(by);
if (wElement != null) {
return wElement;
}
return null;
}
}));
} catch (Exception e) {
System.out.println("Couldn't find the element - " + by);
}
return element;
}
方法2:重载方法1,加入检查次数,即一次timeout不成功再进行一次
public WebElement waitfor(final By by, int checkTimes, int timeout) {
int i=0;
WebElement element = null;
do{
i++;
element = waitfor(by, timeout);
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
}
}while(element==null | i<=checkTimes);
return element;
}