在我们做自动化测试时,一定会出现一种情况取不到界面元素,主要愿意在与界面元素的加载与我们访问页面的时机不一致,一后一前。有可能是界面要素过多或者网络较慢,界面加载中;为此selenium提供了等待方式来解决此种问题,分为显式等待与隐式等待。
显式等待
处理方式1:通过线程等待函数,让自动化测试做一定时间的等待,Thread.sleep(1000);
使用此方法会出现两种不能避免的情况:1.若设置的时间较短,仍不能解决上述问题;2.若设置时间较长,会花费大量的等待时间。我们很难去确定等待时间的长度,因为加载时间的长度会受到外部环境的影响,比如:网络情况,应用的大小,主机的配置情况,主机的内存和CPU的消耗情况。
处理方式2:就是明确的等到界面某元素出现或者某可点击等条件为止,否则一致等待至设定的时间之后跑出异常情况。
采用WebDriverWait类 + ExceptedConditions接口,
方法1:在10秒以内等到该元素出现,则往下执行;否则超过10秒,依然找不到,就抛出异常.
new WebDriverWait(driver,10).until(
ExpectedConditions.presenceOfElementLocated(By.cssSelector("css locator")));
可以改编为更为简洁的方式:
WebElement elementId = (new WebDriverWait( driver, 10)).until(
new ExpectedCondition
(){
@Override
public WebElement apply(WebDriver d){
return d.findElement( By.id("id locator"));
}
}
);
隐式等待
先看一个例子
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
表示为,程序等待5秒继续执行,个人不建议使用该方式。
以下为相关的方法简要说明
// waitForElementPresent locator 等待直到某个元素在页面中存在
// waitForElementNotPresent locator 等待直到某个元素在页面中不存在
//
// waitForTextPresent text 等待直到某个文本在页面中存在
// waitForTextNotPresent text 等待直到某个文本在页面中不存在
//
// waitForText locator text 等待直到locator指定元素内的文本符合text
// waitForNotText locator text 等待直到locator指定元素内的文本不符合text
//
// waitForVisible locator 等待直到locator指定元素在页面中可见
// waitForNotVisible locator 等待直到locator指定元素在页面中不可见
//
// waitForTitle title 等待直到页面标题符合所指定的title
// waitForNotTitle title 等待直到页面标题不符合所指定的title
// waitForLocation url 等待直到页面的地址符合所指定的url
// waitForNotLocation url 等待直到页面的地址不符合所指定的url
//
// waitForValue locator value 等待直到locator指定的元素的value值符合指定的值
// waitForNotValue locator value 等待直到locator指定的元素的value值不符合指定的值
//
// waitForAttribute locator@attr value 等待直到locator指定的元素的attr属性值符合指定的值
// waitForNotAttribute locator@attr value 等待直到locator指定的元素的attr属性值不符合指定的值
//
// waitForChecked locator 等待直到locator指定的radio或checkbox成为选中状态
// waitForNotChecked locator 等待直到locator指定的radio或checkbox成为非选中状态
//
// waitForEditable locator 等待直到locator指定的input或textarea元素可编辑
// waitForNotEditable locator 等待直到locator指定的input或textarea元素不可编辑
// waitForXpathCount xpath count 等待直到页面符合xpath的数量为count
// waitForNotXpathCount xpath count 等待直到页面符合xpath的数量不为count
//
// waitForEval script pattern 等待直到script的执行结果符合pattern
// waitForNotEval script pattern 等待直到script的执行结果不符合pattern