使用java在selenium webdriver中放置driver.wait的有效方法

时间:2018-04-09 18:45:05

标签: java selenium selenium-webdriver

public class menupageProperty{
  public static WebElement administrativeModule(WebDriver driver) {
   private static WebElement menuElement= null; 
   menuElement= driver.findElement(By.linkText("ADMINISTRATIVE MODULE"));
   return menuElement;
  }
  public static WebElement editModule(WebDriver driver) {
   private static WebElement menuElement= null; 
   menuElement= driver.findElement(By.linkText("Edit MODULE"));
   return menuElement;
  }
}

public class runAutomation {
  public static void main(String[] args) throws IOException, InterruptedException{
    menupageProperty.administrative_Module(driver).click();
    Thread.sleep(2000);
    menupageProperty.userMgmtClick(driver).click();
    Thread.sleep(4000);
    menupageProperty.edituser(driver).click();
 }
}

我有这样的元素。我想在两次点击之间放置thread.sleep或等待时间。目前我很难编写为Thread.sleep(4000)。请帮助我以有效的方式编写,或者更确切地说,放置Thread.sleep是不正确的方法。

4 个答案:

答案 0 :(得分:1)

我会推荐这样的东西:

void waitForElementToLoad(WebElement webElement) {
    WebElement element = webDriverWait.until(ExpectedConditions.elementToBeClickable(webElement));
}

传入您在下次点击时等待的元素,并等待其可点击。这应该消除了为每个硬编码时间的需要,并且您可以依赖于您指定的webDriverWait时间。

答案 1 :(得分:0)

  

你可以在这里使用隐式等待,作为一种好的做法,如果有的话   点击中的某些元素然后你可以使用fluentwait   在您可以阅读的给定时间内以给定间隔轮询元素   here

示例代码:

// Waiting 30 seconds for an element to be present on the page, checking

  // for its presence once every 5 seconds.

  Wait wait = new FluentWait(driver)

    .withTimeout(30, SECONDS)

    .pollingEvery(5, SECONDS)

    .ignoring(NoSuchElementException.class);

  WebElement foo = wait.until(new Function() {

    public WebElement apply(WebDriver driver) {

    return driver.findElement(By.id("foo"));

    }

   });

答案 2 :(得分:0)

这是一个等待元素显示在DOM

中的方法

Ps:公开驱动程序并将其作为参数传递

并不是一个好习惯
public void waitIfNotPresent(WebElement element) {
        webElementWait.until(driver -> {
            try {
                return !element.isDisplayed();
            }
            catch (NoSuchElementException e) {
                return true;
            }
        });

答案 3 :(得分:0)

最简单的方法是使用wait加载元素

  WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@text='Welcome']")));

但是如果你想等到某个ajax请求完成后再使用这个

new WebDriverWait(driver, 180).until(new  ExpectedCondition<Boolean>() 
{ public Boolean apply(WebDriver  driver) 
{ JavascriptExecutor js = (JavascriptExecutor) driver;
 return (Boolean) js.executeScript("return jQuery.active == 0"); 
}

});