標籤:
1.隱式等待
implicitlyWait():
當使用了隱士等待執行測試的時候,如果 WebDriver沒有在 DOM中找到元素,將繼續等待,超出設定時間後則拋出找不到元素的異常
當尋找元素或元素並沒有立即出現的時候,隱式等待將等待一段時間再尋找 DOM,預設的時間是0
一旦設定了隱式等待,則它存在整個 WebDriver 對象執行個體的聲明周期中,隱式的等到會讓一個正常響應的應用的測試變慢,
它將會在尋找每個元素的時候都進行等待,這樣會增加整個測試執行的時間。
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
2.顯示等待
WebDriverWait():webdriver的針對某個元素的明確等待(explicitly wait)
詳細格式如下:
WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)
driver - WebDriver 的驅動程式(Ie, Firefox, Chrome 或遠程)
timeout - 最長逾時時間,預設以秒為單位
poll_frequency - 休眠時間的間隔(步長)時間,預設為0.5 秒
ignored_exceptions - 逾時後的異常資訊,預設情況下拋NoSuchElementException 異常。
1 /** 2 * 在給定的時間內去尋找元素,如果沒找到則逾時,拋出異常 3 * */ 4 public static void waitForElementToLoad(WebDriver driver, int timeOut, final By By) { 5 try { 6 (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() { 7 8 public Boolean apply(WebDriver driver) { 9 WebElement element = driver.findElement(By);10 return element.isDisplayed();11 }12 });13 } catch (TimeoutException e) {14 Assert.fail("逾時!! " + timeOut + " 秒之後還沒找到元素 [" + By + "]");15 }16 }
Selenium Webdriver——設定等待時間