在自動化測試過程當中,受網絡、測試設備等諸多因素的影響,我們經常需要在自動化測試腳本中添加一些延時來更好的定位元素來進行一系列的操作。
一般有這么幾種方式:
1.implicitlyWait。識別對象時的超時時間。過了這個時間如果對象還沒找到的話就會拋出NoSuchElement異常
2.setScriptTimeout。異步腳本的超時時間。webdriver 可以異步執行腳本,這個是設置異步執行腳本腳本返回結果的超時時間。
3.pageLoadTimeout。頁面加載時的超時時間。因為webdriver 會等頁面加載完畢在進行后面的操作,所以如果頁面在這個超時時間內沒有加載完成,那么webdriver 就會拋出異常。
4.Thread.sleep()。這是一種掛起線程然后重新喚醒的方式,不建議使用,占用系統線程資源。
package com.testngDemo;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
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 Demo_TimeControl {
public static void main(String args[])
{
WebDriver driver=new FirefoxDriver();
driver.get("http://www.baidu.com");
//設置延時操作
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);//-----頁面加載時間
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);//------元素等待時間(隱式等待)
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);//----腳本執行時間
//顯式等待
WebElement e = (new WebDriverWait(driver, 10)) .until(
new ExpectedCondition< WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("kw"));
}
}
);
}
/**
* 自定義顯式等待
* @param driver
* @param by
* @return
*/
private static WebElement webelementExplicitWait(WebDriver driver,By by)
{
return (new WebDriverWait(driver, 10)) .until(
new ExpectedCondition< WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(by);
}
}
);
}
/**
* 判斷元素是否存在
* @param driver
* @param by
* @return
*/
private static boolean isPresentElement(WebDriver driver,By by)
{
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}catch(Exception e){
return false;
}
}
}
我們可以根據自己的需要來封裝一些元素等待,元素查找的方法,像上面判斷元素是否存在,如果查找不到就拋出異常,有的時候可能是拋錯沒有這樣的元素,有的時候也可能是拋錯元素不可見等錯誤,可以用Excpetion來捕獲。
在timeout接口里就介紹了這前三種時間等待的方法,這里也不細加研究了。
再就是顯式等待ExplicitWait,可以根據我們的需要判讀在一個時間范圍內這個元素是否能定位到,這個作用是比較大的,像上面的方法只是來整體的延時,到底能不能來定位到元素也不知道。但是我們也可以根據自己項目需要來對這些方法進行封裝,使之更好的為我們服務。
