• Selenium Video Tutorials

Selenium - 同步



為了同步指令碼執行和應用程式,我們需要在執行適當的操作後等待。讓我們看看實現相同目標的方法。

Thread.Sleep

Thread.Sleep 是一種靜態等待,它不是在指令碼中使用的很好方法,因為它是在無條件的情況下睡眠。

Thread.Sleep(1000); //Will wait for 1 second.

顯式等待

“顯式等待”會在繼續執行之前等待特定條件發生。當我們想要在物件可見後單擊或操作它時,主要使用它。

WebDriver driver = new FirefoxDriver();
driver.get("Enter an URL"S);
WebElement DynamicElement = 
   (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));

隱式等待

在 WebDriver 由於物件不可用而無法立即找到物件的情況下使用隱式等待。WebDriver 將等待指定的隱式等待時間,並且在此期間不會再次嘗試查詢元素。

一旦超過指定的時限,webDriver 將再次嘗試最後一次搜尋元素。成功後,它繼續執行;失敗後,它丟擲異常。

這是一種全域性等待,這意味著等待適用於整個驅動程式。因此,將此等待硬編碼為較長時間段會影響執行時間。

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("Enter an URL");
WebElement DynamicElement = driver.findElement(By.id("DynamicElement"));

流暢等待

FluentWait 例項定義了等待條件發生的最大時間量,以及檢查物件條件存在的頻率。

假設我們將等待 60 秒才能在頁面上找到一個元素,但我們將每 10 秒檢查一次它的可用性。

Wait wait = 
   new FluentWait(driver).withTimeout(60, SECONDS).pollingEvery(10, SECONDS).ignoring(NoSuchElementException.class);
   
   WebElement dynamicelement = wait.until(new Function<webdriver,webElement>() {
   
   public WebElement apply(WebDriver driver) {
      return driver.findElement(By.id("dynamicelement"));
   }
});
selenium_user_interactions.htm
廣告
© . All rights reserved.