2012-07-31 43 views
51

我正在尋找類似於waitForElementPresent的東西來檢查元素是否在我點擊它之前顯示。我認爲這可以通過implicitWait來完成,所以我用了以下內容:WebDriver - 使用Java等待元素

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); 

然後

driver.findElement(By.id(prop.getProperty(vName))).click(); 

單擊不幸的是,有時等待的元素,有時沒有。我找了一會,發現這個解決方案:

for (int second = 0;; second++) { 
      Thread.sleep(sleepTime); 
      if (second >= 10) 
       fail("timeout : " + vName); 
      try { 
       if (driver.findElement(By.id(prop.getProperty(vName))) 
         .isDisplayed()) 
        break; 
      } catch (Exception e) { 
       writeToExcel("data.xls", e.toString(), 
         parameters.currentTestRow, 46); 
      } 
     } 
     driver.findElement(By.id(prop.getProperty(vName))).click(); 

它等待好了,但在超時之前它不得不等待10次5,50秒。有點多。所以我將隱含的等待時間設置爲1秒,直到現在看起來都很好。因爲現在有些事情在超時之前等待10秒,但其他一些事情在1秒後超時。

你如何覆蓋代碼中存在/可見的等待元素?任何提示都是可觀的。

回答

100

這就是我在我的代碼中做的。

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds); 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>)); 

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>)); 

要精確。針對不同的場景等待快捷方式類似

+1

謝謝!如果我只是早知道這門課程,我的生活會更容易:) – tom 2012-08-02 08:53:26

+0

如何將您的代碼整合到此格式中?\t'@FindBy(how = How.ID,using =「註冊按鈕」) \t WebElement signUpButton;''此外,我仍然得到一個NPE與您的代碼。看起來它試圖獲得elementToBeClickable。當元素未被加載時,我們如何使用這種方法? – HelloWorldNoMore 2016-04-21 00:38:39

-1

上面的等待語句是明確等待的一個很好的例子。

由於顯式等待是侷限於特定Web元素的智能等待(如上述x路徑中所述)。

通過使用顯式等待,你基本上是告訴WebDriver在最大等待X單位(不管你給出了timeoutInSeconds)的時間,然後放棄。

+2

爲您的答案添加一些代碼片段,因爲其他用戶可能會對答案進行不同的分類,而「上方」的上下文可能會因此而改變。 – 2014-10-27 04:45:03

3

您可以使用顯式等待或等待流利等待明確的

示例 - 流利等待的

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20); 
WebElement aboutMe; 
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));  

示例 -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)        
.withTimeout(20, TimeUnit.SECONDS)   
.pollingEvery(5, TimeUnit.SECONDS)   
.ignoring(NoSuchElementException.class);  

    WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {  
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));  
} 
}); 

檢查這個TUTORIAL瞭解更多詳情。

1

我們與elementToBeClickable有很多競賽條件。請參閱https://github.com/angular/protractor/issues/2313。東西沿着這些路線的工作相當不錯,即使有點蠻力

Awaitility.await() 
     .atMost(timeout) 
     .ignoreException(NoSuchElementException.class) 
     .ignoreExceptionsMatching(
      Matchers.allOf(
       Matchers.instanceOf(WebDriverException.class), 
       Matchers.hasProperty(
        "message", 
        Matchers.containsString("is not clickable at point") 
       ) 
      ) 
     ).until(
      () -> { 
       this.driver.findElement(locator).click(); 
       return true; 
      }, 
      Matchers.is(true) 
     ); 
相關問題