Aleks
Aleks

Reputation: 5854

Explicitly wait for X elements to be visible

I want to wait for a certain numbers of elements to be visible on the page.

For this, I'm using:

wait = new WebDriverWait(driver, timeout.getValueInSec());  
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));

Although timeout is long enough, this method returns less elements than I see and expect (2 of 6 in this concrete case). It probably returns as soon as it finds 2 elements, before the rest of them are there.

Is there a way to tell Selenium driver to wait for X elements? Something like:

wait.until(ExpectedConditions.visibilityOfNElementsLocatedBy(6, locator));

Upvotes: 2

Views: 3686

Answers (1)

alecxe
alecxe

Reputation: 473873

It is not difficult to make a custom Expected Condition for your specific requirement:

public static ExpectedCondition<List<WebElement>> visibilityOfNElementsLocatedBy(
      final By locator, final int elementsCount) {
    return new ExpectedCondition<List<WebElement>>() {
      @Override
      public List<WebElement> apply(WebDriver driver) {
        List<WebElement> elements = findElements(locator, driver);

        // KEY is here - we are "failing" the expected condition 
        // if there are less than elementsCount elements
        if (elements.size() < elementsCount) {
          return null;
        }

        for(WebElement element : elements){
          if(!element.isDisplayed()){
            return null;
          }
        }
        return elements;
      }

      @Override
      public String toString() {
        return "visibility of N elements located by " + locator;
      }
    };
  }

Usage:

wait.until(visibilityOfNElementsLocatedBy(locator, 6));

Upvotes: 2

Related Questions