//2秒内加载下面的url,超时会报错
driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
driver.get("https://www.sina.com.cn/");
driver.findElement(By.linkText("新闻")).click();
隐式等待
driver.get("https://www.sina.com.cn/");
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);//隐式等待10s,“新闻”链接
driver.findElement(By.linkText("新闻1")).click();
显示等待
/**
* 获取元素已加载到document树里的元素
* @param by
* @param seconds
* @return
*/
public WebElement getElementLocatedElement(By by,long seconds){
WebDriverWait driverWait=new WebDriverWait(driver,seconds);//显示等待10s,默认500毫秒查找一次
try {
WebElement webElement=driverWait.until(ExpectedConditions.presenceOfElementLocated(by));
return webElement;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取可见元素。
* @param by
* @return
*/
public WebElement getVisibilyElement(By by){
WebDriverWait driverWait=new WebDriverWait(driver,10);//显示等待10s,默认500毫秒查找一次
try {
WebElement webElement=driverWait.until(ExpectedConditions.visibilityOfElementLocated(by));
return webElement;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取
* @param by
* @return
*/
public WebElement getElement(By by){
WebDriverWait driverWait=new WebDriverWait(driver,10);//显示等待30s,默认500毫秒查找一次
try {
String jsStr="return document.readyState=='complete'";//js判断文档加载完成
boolean isReady= (boolean) driverWait.until(ExpectedConditions.jsReturnsValue(jsStr));
if (isReady){
return getVisibilyElement(by);
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Test
public void test1() throws InterruptedException {
driver.get("https://www.sina.com.cn/");
getElement(By.linkText("新闻"),20).click();
}