user2356679
user2356679

Reputation: 371

Selenium WebDriver- FindElements returns elements which are not displayed

Am using Eclipse, TestNG and Selenium 2.32.

List <<f>WebElement> elementOption = driver.findElements(By.xpath("//li[@role='option']"));

The code driver.findElements(By.xpath("//li[@role='option']")); returns all the elements which are not displayed as well. The above 'elementOption' now contains all the elements, even the elements that are not displayed in the webpage. We can use IsDisplayed along with findElement method which will return only the element which is displayed in the webpage. Is there anything similar to IsDisplayed that can be used with findElements which will return only the elements that are displayed?

Upvotes: 4

Views: 19304

Answers (2)

Sameer Patil
Sameer Patil

Reputation: 461

If the elements which you are trying to retrieve contains attributes like style having display values, then you might need to just change your XPATH to get only displayed elements.

List <WebElement> elementOption = driver.findElements(By.xpath("//li[@role='option'][contains(@style,'display: block;')]"));

or

List <WebElement> elementOption = driver.findElements(By.xpath("//li[@role='option'][not(contains(@style,'display: none'))]"));

Upvotes: 1

Yi Zeng
Yi Zeng

Reputation: 32845

In C#, you can create WebDriver extension method like this:

public static IList<IWebElement> FindDisplayedElements<T>(this T searchContext, By locator) where T : ISearchContext {
    IList<IWebElement> elements = searchContext.FindElements(locator);
    return elements.Where(e => e.Displayed).ToList();
}
// Usage: driver.FindDisplayedElements(By.xpath("//li[@role='option']"));

Or use Linq when you call FindElements:

IList<IWebElement> allOptions = driver.FindElements(By.xpath("//li[@role='option']")).Where(e => e.Displayed).ToList();

However, I am aware of that extension methods and Linq don't exist in Java. So you probably need to create you own static method/class using the same logic.

// pseudo Java code with the same logic
public static List<WebElement> findDisplayedElements(WebDriver driver, By locator) {
    List <WebElement> elementOptions = driver.findElements(locator);
    List <WebElement> displayedOptions = new List<WebElement>();
    for (WebElement option : elementOptions) {
        if (option.isDisplayed()) {
            displayedOptions.add(option);
        }
    }
    return displayedOptions;
}

Upvotes: 2

Related Questions