2012-07-31 41 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) 
     ); 
相关问题