1

I'm writing automated tests using Selenium WebDriver and Java that need lots of waits in them to make sure that the appropriate element has loaded before the next action is taken.

I've tried this:

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

which will wait for a specified interval and then fail if the element is not found, and this:

WebDriverWait wait = new WebDriverWait(driver, 100);
wait.until(new ExpectedCondition<Boolean>() {
  public Boolean apply(WebDriver webDriver) {
    System.out.println("Searching for the Companies dropdown");
    return webDriver.findElement(By.id("ctl00_PageContent_vpccompanies_Input")) != null;
  }
});

which will hang indefinitely if the element is not found.

What I'd like is something that would search for the element for a couple of tries and then fail with an error message.

0

2 Answers 2

1

Wrap your code onto a cycle and loop until the find condition matched or extra condition that exits a loop. Use isElementPresent(element) to check that condition of find.

Sign up to request clarification or add additional context in comments.

Comments

0

I would say, put your element access code in a while loop, which breaks either on success or number of attempts.

e.g.(pseudo code)

    int numAttemps = 0;
    int specifiedAttempts = 5;
    boolean success = false;
    do{
       numAttemps++;
       try{
         //access the element
          WebElement element = driver.findElement(By.id(..));
          success  = true; //<--If it reaches here means success
       }catch(NoSuchElementException nse)
           //one attempt failed
       }
     }while(!success || numAttemps <specifiedAttempts);

     if(!success){
        System.out.println("Couldn't load after " +specifiedAttempts+ " attempts");
     }

1 Comment

this doesnt help much in most cases. situation like slow response from server and etc; also, writting a loop to retry tasks is memory consuming

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.