Selenium WebDriver- FindElements returns items that are not displayed

Am uses Eclipse, TestNG, and Selenium 2.32.

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

Code driver.findElements(By.xpath("//li[@role='option']")); returns all items that are also not displayed. The above elementOption element now contains all elements, even elements that are not displayed on the web page. We can use IsDisplayed together with the findElement method, which will return only the element that is displayed on the web page. Is there something similar to IsDisplayed that can be used with findElements that will only return displayed items?

+4
source share
2 answers

In C #, you can create a WebDriver extension method as follows:

 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 know that extension and Linq methods do not exist in Java. Therefore, you probably need to create your 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; } 
+2
source

If the elements you are trying to retrieve contain attributes such as a style that has display values, then you may just need to change the XPATH to get only the display 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'))]")); 
+1
source

Source: https://habr.com/ru/post/1479464/


All Articles