How to work with a List in HTML using Selenium WebDriver

September 20, 2016

Working with List in HTML using WebDriver is an important topic for automation of e-commerce type of projects.

What are Lists?

Lists are a collection of similar type data and make things  presentable and easy to read on a Web Page. There are two types of lists in HTML:

  1. Ordered List – represented by <ol>..</ol> tag. Each list item starts with the <li> tag

Example:

  1. Unordered List – represented by <ul>..</ul> tag. Each list item starts with the <li> tag.

Example:

Let us understand how to iterate over a list. It will be same for both type Ordered and Unordered List. Let us consider below search scenario on any e-commerce site say eBay.in:

  1. Launch browser.
  2. Invoke URL “http://www.ebay.in.”
  3. Enter some value in “Search Product” field. Let’s say we enter “Apple Watches”.
  4. Select the category on your search from the dropdown. Let’s select category as “Watches”.
  5. Click on the Search button.
  6. Get the information of all the products listed out for this search.

Here is the Sample Code:

This example is the continuation of the previous tutorial. The detailed explanation of step 1 to 6 is covered in Working with DropDowns. Let’s focus on Step 7 and 8.

7. Fetching all the WebElements from a List and storing in a Data Structure.

 List<WebElement> allProduct = Driver.findElements(By.xpath(“//ul[@id=’ListViewInner’]/li”));

Whenever we have to fetch more than one WebElement we use List (Data-Structure) from Java.utils. Here, we have declared List of type WebElement, and as we have to locate more than one element we will be using findElements() method. This piece of code above will find the complete listings. Refer Screenshot below-

Fetching the list using XPath locator

Fetching the list using XPath locator

8. Iterating over the List using enhanced for (for-each) loop.

for( WebElement product : allProduct){

System.out.println(product.getText());

System.out.println(“*********************************************************************”);
}

This code  is fetching all the products from listings in WebElement “product” and later  printing each and every product from the total listings. Method used to fetch the text is getText().

Similarly, you can use above code to achieve whatever you desire from a list. If I have to summarise above code. It will be:

  1. Fetch all the WebElements in List (Ordered or Unordered) in a list (Java.Utils) data structure.
  2. Iterate over the list using for-each loop or Iterator.

Hope you enjoyed the above article.

For any questions, queries or comments. Feel free to write us at amrita@qatechhub.com or support@qatechhub.com. Happy learning 🙂

 

Amrita Joshi

About the Author

Amrita Joshi

Leave a Comment: