All IT Courses 50% Off
Selenium Tutorials

How to Handle Web Table in Selenium WebDriver

What is WebTable?

Web tables are basically a group of elements made of rows and columns. It is used to organize information on a web page. When we create a table for a web page it is called a web table. Table is created by using <table> tag in HTML. Web table is an HTML structure used for creating rows and columns on a web page.

 A web table consists of below parts:

  1. Header(s): Using <th> tag header is created
  2. Row(s): Using <tr> tag row is created
  3. Columns(s): Using <td> tag column is created

Types of Web Tables:

Web Tables are categorized into two parts

  1. Static web table:  The Number of rows and columns will be static. Eg. Table of days, months, etc.
  2. Dynamic web table: Number of rows and columns will be dynamically changing, which means that it keeps on increasing or decreasing based on data. Eg: Student table, Customer table.

Web table demo using HTML:

HTML code is very easy to understand and self-descriptive. Let’s create a web table that displays Company name, Contact and Country.

<!DOCTYPE html>
<html>
<head>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}
 
td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}
 
tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
</head>
<body>
 
<table name="CompanyTable">
  <tr>
    <th>CompanyName</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>John</td>
    <td>London</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Jose</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Sam</td>
    <td>Spain</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Paul</td>
    <td>USA</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Jose</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Paul</td>
    <td>UK</td>
  </tr>
</table>
 
</body>
</html>

Save the above html code with .html extension. When we open the above html file in a browser, it will be shown as:

html.PNG

Handling different scenarios of a web table:

1.Print all headers of a web table:

The header of a web table is a row. Header is created using <th> with <tr> tag. Generally, the first row of a table is the header. The below code is used for retrieving header names and print.

print.png
print1.PNG

I am using index (/tr[1]) to find the first row of a table from the above code. Let’s assume the first row in the table will be the header. You can use the below code if you are not sure which row is the header.

print2.PNG
print1.PNG

2. Retrieving and printing the number of rows in a web table

Below code will retrieve and print the number of rows in a web table

print3.PNG

Since the above table contains a row header, we need to exclude the header row from the total number of rows to get an actual number of rows data.

3. Find the number of columns for each row

Web table rows can have a different number of columns. For example, Row1 has 4 columns while Row2 has 3 columns only. By using the below code we can retrieve the number of columns for each row.

print5.PNG
print6.PNG

4. Retrieve the name of Company whose contact is John

Way 1:

In the above table, we know that the 2nd column consists of the contact name. So first we will retrieve the contact name column and will match with the required contact name. If it matches then we will take value from the 1st column which is the company name.

print7.PNG
print8.PNG

Way 2:

 I am using the Xpath text() method which is the more efficient.

print9.PNG
print8.PNG

5. Print last row of a table

We know the number of rows in a web table will keep on changing. In this case, we use the last() method of Xpath.

print10.PNG
print11.PNG

6. Print all data of a table

Below code will print all data of the table

print12.PNG

Let’s create a test case in which we will automate the following scenarios to handle Web Table:

  • Invoke a Google chrome browser.
  • Open URL: https://www.w3schools.com/html/html_tables.asp
  • Find total rows in a web table.
  • Print all company names in a web table
  • Finding “Island Trading” company exists or not in the table and displaying the position
  • Printing all contact names
  • Printing all country names
  • Printing total no of columns
  • Printing all the column values

Now, we will create a test case step by step in order to understand how to handle Web Tables in WebDriver.

Step 1: Launch Eclipse IDE.Step 2: Go to File > New > Click on Java Project.

File.PNG

Step 3: Right- click on the src folder and click on the New > class.

Classname.PNG

Give your Class name as “WebTableHandle” and Select the checkbox “public static void main(String[] args) and click on the “Finish” button.

Classname1.PNG

Step 4: Invoke the Google Chrome browser and set the system property to the path of your chromedriver.exe file.

Here is the sample code to set Chrome driver system property:

// System Property for Chrome Driver   

 System.setProperty(“webdriver.chrome.driver”, “ D:\\Drivers\\geckodriver.exe “);  

After that, we have to initialize the Chrome driver using ChromeDriver Class. Below is the sample code to initialize Chrome driver using ChromeDriver class.

// Instantiate a ChromeDriver class.      

WebDriver driver=new ChromeDriver();  

We will get the below code to launch Google Chrome browser after combining both of the above codes.

 System.setProperty(“webdriver.chrome.driver”, “ D:\\Drivers\\geckodriver.exe “);  

WebDriver driver=new ChromeDriver();  

After that, we need to navigate to the desired URL.

Below is the sample code to navigate to the desired URL:

// Launch Website  driver.navigate().to(“https://www.w3schools.com/html/html_tables.asp “); 

Here is the complete code for above scenario:

import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.chrome.ChromeDriver;  
  
public class WebTableHandle {  
  
    public static void main(String[] args) {  
          
        // System Property for Chrome Driver   
 System.setProperty("webdriver.chrome.driver", “ D:\\Drivers\\geckodriver.exe ");  
  
        // Instantiate a ChromeDriver class.      
    WebDriver driver=new ChromeDriver();  
  
        // Launch Website  
driver.navigate().to("https://www.w3schools.com/html/html_tables.asp ");  
     
    }    
}  

Step 5:  Find a total no of rows in a web table.

List<WebElement>  rows =  driver.findElements(By.xpath("//table[@id='customers']/tbody/tr"));
      int rowCount = rows.size();
      System.out.println("Total no of rows in web table : " + rowCount);

Step 6:  Print all company names in a web table.

//Printing all the Company Names
        String beforeXpath = "//*[@id='customers']/tbody/tr[";
        String afterXpath = "]/td[1]";
        
        for(int i=2; i<=rowCount; i++) {
        	String actualXpath = beforeXpath+i+afterXpath;
        	WebElement element = driver.findElement(By.xpath(actualXpath));
        	System.out.println(element.getText());

Step 7:  Finding “Island Trading” company exists or not in the table and displaying the position

//Finding "Island Trading" company exists or not in the table and displaying the position
        	if(element.getText().equals("Island Trading")) {
        		System.out.println("The company name : " + element.getText() + " is found" + " at the position :"+ (i-1));
        		break;

Step 8:  Printing all contact names in the web table

//Printing all contact names
        //*[@id="customers"]/tbody/tr[2]/td[2]
        
        String afterXpathContact = "]/td[2]";
        for(int i=2; i<=rowCount; i++) {
        	String actualXpath = beforeXpath+i+afterXpathContact;
        	WebElement element = driver.findElement(By.xpath(actualXpath));
        	System.out.println(element.getText());
}

Step 9:  Printing all country names in the web table

 //Printing all country names

        String afterXpathCountry = "]/td[3]";
        for(int i=2; i<=rowCount; i++) {
        	String actualXpath = beforeXpath+i+afterXpathCountry;
        	WebElement element = driver.findElement(By.xpath(actualXpath));
        	System.out.println(element.getText());
        	
        	}

Step 9:  Print Total no of columns in a web table

//print total no of columns
    	//handle webtable columns
    	//*[@id="customers"]/tbody/tr[1]/th[1]------>Company Column XPath
    	//*[@id="customers"]/tbody/tr[1]/th[2]----->Contact Column XPath
    	//*[@id="customers"]/tbody/tr[1]/th[3]----->Country Column XPath
    	

    	
    	String colBeforeXpath = "//*[@id='customers']/tbody/tr[1]/th[";
        String colAfterXpath = "]";
       List<WebElement> cols =  driver.findElements(By.xpath("//*[@id='customers']/tbody/tr[1]/th"));
       int 	colCount = cols.size();
       System.out.println("Total number of columns are " + colCount);

Step 10: Printing all the column values in a web table

 System.out.println("Columns values are: ");
       for(int i=1; i<=colCount; i++) {
    	   
    	   WebElement element = driver.findElement(By.xpath(colBeforeXpath+i+colAfterXpath));
    	   String colText = element.getText();
    	   System.out.println(colText);
       }

Now, our final test script will look something like:

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebTableHandle {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.setProperty("webdriver.chrome.driver", "D:\\Drivers\\geckodriver.exe");

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.w3schools.com/html/html_tables.asp");
        
      //*[@id="customers"]/tbody/tr[2]/td[1]
      //*[@id="customers"]/tbody/tr[3]/td[1]
      //*[@id="customers"]/tbody/tr[4]/td[1]  
      //*[@id="customers"]/tbody/tr[7]/td[1]  
        
     List<WebElement>  rows =  driver.findElements(By.xpath("//table[@id='customers']/tbody/tr"));
      int rowCount = rows.size();
      System.out.println("Total rows in web table : " + rowCount);
        //Printing all the Company Names
        String beforeXpath = "//*[@id='customers']/tbody/tr[";
        String afterXpath = "]/td[1]";
        
        for(int i=2; i<=rowCount; i++) {
        	String actualXpath = beforeXpath + i + afterXpath;
        	WebElement element = driver.findElement(By.xpath(actualXpath));
        	System.out.println(element.getText());
        	
        	//Finding "Island Trading" company exists or not in the table and displaying the position
        	if(element.getText().equals("Island Trading")) {
        		System.out.println("The company name : " + element.getText() + " is found" + " at the position :"+ (i-1));
        		break;
        	}
        }
        
        System.out.println("***********************");
        
        //Printing all contact names
        //*[@id="customers"]/tbody/tr[2]/td[2]
        
        String afterXpathContact = "]/td[2]";
        for(int i=2; i<=rowCount; i++) {
        	String actualXpath = beforeXpath+i+afterXpathContact;
        	WebElement element = driver.findElement(By.xpath(actualXpath));
        	System.out.println(element.getText());
        	
        	}
        
        System.out.println("***********************");
        //Printing all country names

        String afterXpathCountry = "]/td[3]";
        for(int i=2; i<=rowCount; i++) {
        	String actualXpath = beforeXpath+i+afterXpathCountry;
        	WebElement element = driver.findElement(By.xpath(actualXpath));
        	System.out.println(element.getText());
        	
        	}
        
      //print total no of columns
    	//handle webtable columns
    	//*[@id="customers"]/tbody/tr[1]/th[1]------>Company Column XPath
    	//*[@id="customers"]/tbody/tr[1]/th[2]----->Contact Column XPath
    	//*[@id="customers"]/tbody/tr[1]/th[3]----->Country Column XPath
    	

    	
    	String colBeforeXpath = "//*[@id='customers']/tbody/tr[1]/th[";
        String colAfterXpath = "]";
       List<WebElement> cols =  driver.findElements(By.xpath("//*[@id='customers']/tbody/tr[1]/th"));
       int 	colCount = cols.size();
       System.out.println("Total number of columns are " + colCount);
       
	   System.out.println("Columns values are: ");
       for(int i=1; i<=colCount; i++) {
    	   
    	   WebElement element = driver.findElement(By.xpath(colBeforeXpath+i+colAfterXpath));
    	   String colText = element.getText();
    	   System.out.println(colText);
       }

        
        }
	
	   
        	
	}

Step 11: Right-Click on the Eclipse and select the option Run As > Java Application.

After running, the above test script will launch the Chrome browser and display the output.

output.PNG
Facebook Comments
Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button
Close
Close

Get Selenium Training Online
Course Now at 50%OFF!

Offer valid for 1st 20 seats only, Hurry up!!

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

H2kinfosys will use this information to be in touch with you for providing updates.