Pavan T
Pavan T

Reputation: 756

How to get list of webElements which is visible only in page

I wanted to get the list of element which currently present on page as some content hide in page that I don't want to access.

Upvotes: 0

Views: 3044

Answers (3)

JeffC
JeffC

Reputation: 25597

There are a couple approaches that I would recommend.

  1. Find a locator that only finds the visible desired elements. This sometimes happens on website when there are different versions of the site, e.g. mobile, desktop, etc.

  2. If #1 doesn't work, we can create a method that takes a locator, finds all elements, and then filters the list down to only those that are visible.

    public List<WebElement> findVisibleElements(By locator) {
        return driver.findElements(locator).stream().filter(e -> e.isDisplayed()).collect(Collectors.toList());
    }
    

    You would then use it like

    List<WebElement> inputs = SeleniumSandbox.findVisibleElements(By.id("someId"));
    // this is for debugging purposes and should be the count of matching visible elements
    System.out.println(inputs.size());
    // this sends "some text" to the first visible element
    inputs.get(0).sendKeys("some text");
    

Upvotes: 0

Barry Knapp
Barry Knapp

Reputation: 2889

public static void logVisible(WebDriver driver, String couldNotFind) {



     logger.error("Could not find element "+couldNotFind+", but here is what was actually on the page");

     driver.findElements(By.xpath("//*[self::div or self::input or self::li  or self::ul or self::button]")).stream()
    .filter(s -> s.isDisplayed())
    .forEach(s -> logger.error(String.format("Visible : Id:%s Tag:%s Class:%s Text:%s",
      s.getAttribute("id"), s.getTagName(), s.getAttribute("class"), s.getText()).replaceAll("  ", " ").replaceAll("\n", " ")));



 }

Upvotes: 0

nilesh
nilesh

Reputation: 14289

Assuming you are using Java, you can use ExpectedConditions and do something like,

WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 300/*timeOutInSeconds*/);
ExpectedCondition<List<WebElement>> condition = ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("foo")) 
List<WebElement> allVisibleElements = wait.until(condition);

Upvotes: 1

Related Questions