selenium webdriver学习------------如何等待页面元素加载完成
web的自动化测试中,我们经常会遇到这样一种情况:当我们的程序执行时需要页面某个元素,而此时这个元素还未加载完成,这时我们的程序就会报错。怎么办?等待。等待元素出现后再进行对这个元素的操作。
在selenium-webdriver中我们用两种方式进行等待:显性的等待和隐性的等待。
1 .显性等待
明确的等待是指在代码进行下一步操作之前等待某一个条件的发生。最不好的情况是使用Thread.sleep()去设置一段确认的时间去等待。但为什么说最不好呢?因为一个元素的加载时间有长有短,你在设置sleep的时间之前要自己把握长短,太短容易超时,太长浪费时间。selenium webdriver提供了一些方法帮助我们等待正好需要等待的时间。
利用WebDriverWait类和ExpectedCondition接口就能实现这一点。
下面的html代码实现了这样的一种效果:点击click按钮5秒钟后,页面上会出现一个红色的div块。我们需要写一段自动化脚本去捕获这个出现的div,然后高亮之。
Wait.html
<html>
<head>
<title>Set Timeout</title>
<style>
.red_box {background-color: red; width = 20%; height: 100px; border: none;}
</style>
<script>
function show_div(){
setTimeout("create_div()", 5000);
}
function create_div(){
d = document.createElement('div');
d.className = "red_box";
document.body.appendChild(d);
}
</script>
</head>
<body>
<button id = "b" onclick = "show_div()">click</button>
</body>
</html>
下面的代码实现了高亮动态生成的div块的功能
import java.util.concurrent.TimeUnit;
import main.java.com.hx.utilities.Log;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WaitForSomthing {
/**
* @author aerchi and juan
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.firefox.bin","D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
WebDriver dr = new FirefoxDriver();
String url = "file:///D:/Wait.html";// "%Path%/to/Wait.html"
dr.get(url);
//显示等待
WebDriverWait wait = new WebDriverWait(dr,10);
wait.until(new ExpectedCondition<WebElement>(){
public WebElement apply(WebDriver d) {
return d.findElement(By.id("b"));
}}).click();
//按道理需要在这同样设置等待red_box 元素加载显示,因为html 文件设置的是点击click按钮5s 后才会出现那个红色区域,所以此处不设置等待,会报错显示元素找不到,这就可以想到隐性等待中的影响整个生命周期这点不同
WebElement element = dr.findElement(By.cssSelector(".red_box"));
((JavascriptExecutor)dr).executeScript("arguments[0].style.border = \"5px solid yellow\"",element);
}
}
上面的代码WebDriverWait类的构造方法接受了一个WebDriver对象和一个等待最长时间(10秒)。然后调用until方法,其中重写了ExpectedCondition接口中的apply方法,让其返回一个WebElement,即加载完成的元素,然后点击。
默认情况下,WebDriverWait每500毫秒调用一次ExpectedCondition,直到有成功的返回,当然如果超过设定的值还没有成功的返回,将抛出异常。
2. 隐性等待
隐性等待是指当要查找元素,而这个元素没有马上出现时,告诉WebDriver查询Dom一定时间。默认值是0,但是设置之后,这个时间将在WebDriver对象实例整个生命周期都起作用。上面的代码就变成了这样:
import java.util.concurrent.TimeUnit;
import main.java.com.hx.utilities.Log;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WaitForSomthing {
/**
* @author aerchi and juan
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.firefox.bin","D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
WebDriver dr = new FirefoxDriver();
String url = "file:///D:/Wait.html";// "%Path%/to/Wait.html"
dr.get(url);
//隐式等待
dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
dr.findElement(By.id("b")).click();
WebElement element = dr.findElement(By.cssSelector(".red_box"));
((JavascriptExecutor)dr).executeScript("arguments[0].style.border = \"5px solid yellow\"",element); //高亮显示红框区域
}
}
补充:------------------------------------------------------------------------------------------------------------------------------------------------------------
显性等待的条件
等待的条件 | WebDriver方法 |
页面元素是否在页面上可用和可被单击 | elementToBeClickable(By locator) |
页面元素处于被选中状态 | elementToBeSelected(WebElement element) |
页面元素在页面中存在 | presenceOfElementLocated(By locator) |
在页面元素中是否包含特定的文本 | textToBePresentInElement(By locator) |
页面元素值 | textToBePresentInElementValue(By locator, java.lang.String text) |
标题 (title) | titleContains(java.lang.String title) |
代码可修改为:
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".red_box")));
WebElement element = driver.findElement(By.cssSelector(".red_box"));
((JavascriptExecutor)driver).executeScript("arguments[0].style.border = \"5px solid yellow\"",element);
}
前面介绍的显性等待用的是自定义条件的new ExpectedCondition<WebElement> 形式的等待条件;
jdk 1.8 的可以用lambda 去自定义,这块我还需要需要。谢谢我的qq 好友,深圳的kfur77。
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
目前理解区别:
1. 显性等待是等待某个条件的出现,再去执行后面的操作 ,可以是自定义的条件去重写apply 方法。元素查找机制是webDriver框架定义的每500ms 查找一次,查找到就终止查询;在定义的超时时间内未找到元素就抛异常; (这个500ms的查找频率可以自定义 如:WebDriverWait wait = new WebDriverWait(dr,10,500) )
2. 隐性等待是查询dom ,查询机制待考究(说是会等页面的全部元素加载完成才会进行下一步?)。若显性等待的自定义条件为dom 的话,两者没有任何区别;
唯一最大的区别是,隐性等待影响的是driver的整个生命周期;
3. 显性等待和隐性等待可以同时使用,在其他元素中遵循隐性等待(整个生命周期嘛),在WebDriverWait这个元素中显性等待起主要作用,但是最大等待时间取决于两者中的最大者,若隐性最大等待时间>显性,则最大等待时间为隐性等待设置的时间;
补充:
dom 的定义http://www.w3school.com.cn/htmldom/dom_intro.asp 本文中是html dom,关于如何获取,修改,添加或者删除html 元素的标准。