Web Automation Using Selenium
  • About The Book
  • Selenium
    • Introduction
      • What is testing and why?
      • What is Selenium and Why?
    • Getting Started
      • Audience
      • Prerequisite
      • Set up
      • Getting Started - Hello World..!!
      • What are drivers
    • Locators
      • CSS Selectors
      • XPath Selector
    • WebDriver
      • WebDriver Methods
      • WebDriver Types
    • WebElement(s)
      • WebElement Methods
      • Looping Through WebElements
    • Waits In Selenium
  • TestNG
    • Introduction
    • TestNG Setup
    • First Test Script
    • Some of the features of TestNG
    • TestNG Annotations
      • @Test
      • @DataProvider
  • Maven
    • Introduction
  • Framework Development
    • Introduction
    • Building Framework
      • Technology Stack
      • Page Object Model (POM)
      • Setup
      • What our framework contain
      • Packages
        • Context
        • Factory
        • Listeners
        • Pages
      • Creating first automation test
  • Common Interview Questions
    • Selenium-Related
Powered by GitBook
On this page

Was this helpful?

  1. Selenium
  2. WebElement(s)

Looping Through WebElements

Looping through list of web elements

As discussed sometimes list of web elements have advantages over identifying a single element.

List of web elements is essentially a java.util.List of WebElement interface, i.e., we can leverage all that we can do on a normal java list, like Filtering, sorting, getting element at desired index, etc.,

Examples:

Getting element at a desired index

WebElement desiredElement = elements.get(2);
// Note : Index starts from zero.

Filtering only visible elements in list of elements:

List<WebElement> elements = driver.
					  findElements(By.id("common-id-of-the-elelemnts"));
		
for(WebElement element : elements) {
	if(!element.isDisplayed()) {
		elements.remove(element);
	}
}

//java8 way
elements.stream().
			filter(element -> element.isDisplayed()).
			collect(Collectors.toList());

Filtering only elements which contain certain text :

List<WebElement> elements = driver.
					  findElements(By.id("common-id-of-the-elelemnts"));
		
for(WebElement element : elements) {
	if(element.getText().contains("desiredtext")) {
		elements.remove(element);
	}
}

//java8 way
elements.stream().filter(element -> 
			element.getText().
			contains("desiredtext")).collect(Collectors.toList());
PreviousWebElement MethodsNextWaits In Selenium

Last updated 5 years ago

Was this helpful?