【selenium3+JAVA】介面自動化測試教程(五)——等待設定
阿新 • • 發佈:2018-12-11
超時設定分為三種,分別為顯性等待,隱性等待和強制等待,如下所示:
1、隱式等待
此等待方式為全域性共用,此處共有三個方法,分別為查詢元素的等待超時時間、頁面載入等待超時時間和js指令碼執行超時時間,方法如下程式碼所示
System.setProperty("webdriver.chrome.driver", "D:\\test\\driver\\chromedriver.exe");
ChromeDriver chrome = new ChromeDriver();
//此處為設定頁面載入超時時間為30s
chrome.manage().timeouts().pageLoadTimeout(30, TimeUnit. SECONDS);
//此處為設定元素查詢最長超時時間為10s
chrome.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//此處為設定js指令碼執行超時時間為30s
chrome.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
2、強制等待
此種等待方法直接呼叫Thread.sleep()方法來進行執行緒等待,由於此方法較為死板,不夠靈活,會導致指令碼執行時間變長,故建議儘量少用,封裝方法如下:
public static void wait(int second)
{
try {
Thread.sleep(second*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3、顯式等待
此種方式用於特定元素、特定條件的等待,使用靈活,建議使用這種方法來進行等待設定,基本操作操作方法如下:
System.setProperty("webdriver.chrome.driver", "D:\\test\\driver\\chromedriver.exe");
ChromeDriver chrome = new ChromeDriver();
try {
WebDriverWait wait = new WebDriverWait(chrome, 10, 100);
// 每隔100毫秒去呼叫一下until中的函式,預設是0.5秒,如果等待10秒還沒有找到元素 。則丟擲異常。
wait.until(new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver driver) {
driver.findElement(By.id("kw"));
return driver.findElement(By.id("kw"));
}
}).sendKeys("我是一個自動化測試小指令碼");
} finally {
chrome.close();
}
檢視原始碼我們可以看到如下程式碼:
/**
* Wait will ignore instances of NotFoundException that are encountered (thrown) by default in
* the 'until' condition, and immediately propagate all others. You can add more to the ignore
* list by calling ignoring(exceptions to add).
*
* @param driver The WebDriver instance to pass to the expected conditions
* @param timeOutInSeconds The timeout in seconds when an expectation is called
* @see WebDriverWait#ignoring(java.lang.Class)
*/
public WebDriverWait(WebDriver driver, long timeOutInSeconds) {
this(
driver,
java.time.Clock.systemDefaultZone(),
Sleeper.SYSTEM_SLEEPER,
timeOutInSeconds,
DEFAULT_SLEEP_TIMEOUT);
}
如上方法中只有driver引數和timeout引數,其他幾個引數都是在函式內部設定的預設引數,Clock和Sleeper都是使用系統預設,而DEFAULT_SLEEP_TIMEOUT則使用的如下這個,500ms:
protected final static long DEFAULT_SLEEP_TIMEOUT = 500;
其他幾個方法大同小異,區別在於引數變為輸入的了,故一般使用前面給出的列子中的那個方法就好;
本例子中給出的是自己自定義until中的condition,但是實際上selenium已經提供了一些常用的條件,放在類ExpectedConditions
中,如下所示;
這些方法基本上通過名字就可以看出來其大致用途,所以此處就不再詳述了,使用方法參考如下程式碼:
System.setProperty("webdriver.chrome.driver", "D:\\test\\driver\\chromedriver.exe");
ChromeDriver chrome = new ChromeDriver();
//如下為超時時間為10s,查詢間隔時間為100ms
WebDriverWait wait = new WebDriverWait(chrome, 10, 100);
wait.until(ExpectedConditions.alertIsPresent());