What Is an HTML Static Web Table?
The table is nothing but a Structure of HTML data where we create the structure or format with the help of <table> tag and <tr>,<td> tags. You Can find some other tags that are used during the creation time of a table. From those above tags, the:
- <table> tag represents the starting of a table
- <tr> tag defines the row
- <td> defines the column
- <th> for heading
Different types of Web Tables
According to the behavior of the tables, they are categorized into 2 types
- Static Table: This table type defines the number of rows and columns.
- Dynamic Table: In this type of table, the number of rows and columns is fixed; it depends on the data based on the data, and the number of rows or columns may be increased or decreased.
Static Demo Table
The table below is a static demo table, and the HTML code for the table:
<html> <head> <style> </style> </head> <body> <table name="BookTable"> <tr> <th>BookName</th> <th>Author</th> <th>Subject</th> <th>Price</th> </tr> <tr> <td>Learn Selenium</td> <td>Amit</td> <td>Selenium</td> <td>300</td> </tr> <tr> <td>Learn Java</td> <td>Mukesh</td> <td>Java</td> <td>500</td> </tr> <tr> <td>Learn JS</td> <td>Animesh</td> <td>Javascript</td> <td>300</td> </tr> <tr> <td>Master In Selenium</td> <td>Mukesh</td> <td>Selenium</td> <td>3000</td> </tr> <tr> <td>Master In Java</td> <td>Amod</td> <td>JAVA</td> <td>2000</td> </tr> <tr> <td>Master In JS</td> <td>Amit</td> <td>Javascript</td> <td>1000</td> </tr> </table> </body> </html>
If the above code save “filename.html”, then you can save it from getting an HTML table like the one below.
BookName | Author | Subject | Price |
---|---|---|---|
Learn Selenium | Amit | Selenium | 300 |
Learn Java | Mukesh | Java | 500 |
Learn JS | Animesh | Javascript | 300 |
Master In Selenium | Mukesh | Selenium | 3000 |
Master In Java | Amod | JAVA | 2000 |
Master In JS | Amit | Javascript | 1000 |
How to Handle Static Table Elements
There is nothing complicated in handling the table elements or cells. All you can do is inspect the table cell and get that. For that, you can use the different locators, but if you are not aware of those, you can write a common locator that helps you locate the elements with the XPath locators.
Below, we will discuss a few scenarios of how you can retrieve the required data from different rows or columns of the table.
How to print all the table header values.
As you can see, header values are a row with <th> and <tr> tags. So let us go to understand how we can retrieve the values from the table:
1. Locate the complete table header, which is the first row. so we need to locate and complete the full header with the Xpath locators, and after that, we can retrieve each cell value by a loop.
package com.selenium.practice.table; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class StaticTable_FindTableHeaderEx { public static void main(String[] args) { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); //When The Checkboxes have an Unique ID driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://softwaretestingo.blogspot.com/2020/09/static-table.html"); driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); List<WebElement> allHeadersOfTable= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr/th")); System.out.println("Headers in table are below:"); System.out.println("Total headers found: "+allHeadersOfTable.size()); for(WebElement header:allHeadersOfTable) { System.out.println(header.getText()); } } }
Find the number of columns for each row:
For a static table, the column is always the same for all the columns, but when dealing with a dynamic table, you can find out that some row sizes are different. So, in that case, how do you find the number of cells in each row using the below script
package com.selenium.practice.table; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class StaticTable_FindNuberOfColumns { public static void main(String[] args) { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); //When The Checkboxes have an Unique ID driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://softwaretestingo.blogspot.com/2020/09/static-table.html"); driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); List<WebElement> allRows= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr")); // We will start from 2nd row as 1st row is header for(int i=2;i<=allRows.size();i++) { List<WebElement> allColumnsInRow=driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td")); System.out.println("Number of columns in "+(i-1)+" data row is:"+allColumnsInRow.size()); } driver.close(); } }
Retrieve the name of the book whose author is Mukesh:
In the above table, you can see that the second column is for an author, so first, we will try to get the author’s name, and with that value, we will match it with the given author value. If both the values are matched, we will get the book name value from the first column because that represents the book name.
package com.selenium.practice.table; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class StaticTable_FindBooksWrittenByMukesh { public static void main(String[] args) { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); //When The Checkboxes have an Unique ID driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://softwaretestingo.blogspot.com/2020/09/static-table.html"); driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); List<WebElement> allRows= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr")); // We will start from 2nd row as 1st row is header for(int i=2;i<=allRows.size();i++) { WebElement authorColumn=driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td[2]")); if(authorColumn.getText().toLowerCase().equalsIgnoreCase("Mukesh")) { WebElement bookNameColumns=driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td[1]")); System.out.println(bookNameColumns.getText()); } } driver.close(); } }
The other way we can do the same thing with the help of the text() method. In this way, we are trying to locate all those author names whose names are Mukesh, and based on that, we will select the book name.
package com.selenium.practice.table; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class StaticTable_FindBooksWrittenByMukeshAnotherWay { public static void main(String[] args) { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); //When The Checkboxes have an Unique ID driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://softwaretestingo.blogspot.com/2020/09/static-table.html"); driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); System.out.println("Books written by Mukesh are below:"); List<WebElement> allColumnsInRow=driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr/td[text()='Mukesh']/../td[1]")); for(WebElement e: allColumnsInRow) { System.out.println(e.getText()); } driver.close(); } }
List all books whose price is greater than or equal to 1000
We can do this by like below
package com.selenium.practice.table; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class StaticTable_FindBooksWhosePriceisMoreThen1000 { public static void main(String[] args) { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); //When The Checkboxes have an Unique ID driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://softwaretestingo.blogspot.com/2020/09/static-table.html"); driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); List<?> allRows= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr")); // Print book name whose price is greater than and equal to 1000 System.out.println("Books with price greater than and equal to 1000 are below:"); for(int i=2;i<=allRows.size();i++) { WebElement priceColumn=driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td[4]")); if(Integer.parseInt(priceColumn.getText())>=1000) { WebElement bookName=driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td[1]")); System.out.println(bookName.getText()); } } driver.close(); } }
Print the last row of the table
During the discussion on Xpath, we discussed last(). We can use the same method here to select the last row; after that, we can use a loop to get the values of the cells of that row.
The total print cost of all the books listed in the table
We can also collect the value of each cell of the price column by using the text() method, and then we can convert those string values into an integer. After that, we can add all those values to get the total values.
package com.selenium.practice.table; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class StaticTable_FindTotalCostsOfAllBooks { public static void main(String[] args) { WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); //When The Checkboxes have an Unique ID driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://softwaretestingo.blogspot.com/2020/09/static-table.html"); driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); // find the sum of the cost of all books listed List<WebElement> costColumns= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr/td[4]")); int sum_price=0; for(WebElement e : costColumns) { sum_price= sum_price+Integer.parseInt(e.getText()); } System.out.println("total price: "+sum_price); driver.close(); } }
Retrieving the cell value of a specific column of a specific row
We can mention the specific row and column value in the XPath to get only our required value from the table to get a specified cell value.
// Retrive cell value by providing row and column number WebElement colValue= driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr[2]/td[3]")); System.out.println(colValue.getText());
the above method is static, but we can customize the same method so that by only passing the row and column value to that method, we can easily get that value.
public static String getColValue(int row, int col, WebDriver driver) { WebElement colValue= driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+row+"]/td["+col+"]")); return colValue.getText(); }
Finding column index using the column name
Suppose you want to get the average value of the price, but you don’t know which column is for the price; in this case, we need to get all the values of the header, and after that, we need to iterate each header value and need to compare with the price. If the table header value matches the price column name, we can get the count, and from that, we can get the index.
// Printing column index based on column name List allHeadersOfTable2= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr[1]/th")); for(int k=0;k<allHeadersOfTable2.size();k++) { if(allHeadersOfTable2.get(k).getText().equalsIgnoreCase("price")) { System.out.println("Column index of Price column is: "+(k+1)); } }
The Complete Program
package com.selenium.practice.table; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class HandlingWebTable { public static void main(String[] args) { System.out.println("Execution Starts"); WebDriver driver; System.setProperty("webdriver.chrome.driver","Path Of Browser Driver"); //When The Checkboxes have an Unique ID driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://softwaretestingo.blogspot.com/2020/09/static-table.html"); driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS); // Printing table header of a web table assuming first row as header System.out.println("Printing all header of table assuming first row as header: "); List<WebElement> allHeadersOfTable= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr[1]/th")); System.out.println("Headers in table are below:"); System.out.println("Total headers found: "+allHeadersOfTable.size()); for(WebElement header:allHeadersOfTable) { System.out.println(header.getText()); } System.out.println("=================================="); // Printing table header of a web table assuming no information about header row System.out.println("Printing all header of table without information of row header "); List<WebElement> allHeadersOfTable1= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr/th")); System.out.println("Headers in table are below:"); System.out.println("Total headers found: "+allHeadersOfTable1.size()); for(WebElement header:allHeadersOfTable1) { System.out.println(header.getText()); } System.out.println("=================================="); // Finding number of rows in a web table. We need to exclude header to get actual number of data rows System.out.println("Retrieving total number of data rows:"); List<WebElement> allRows= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr")); System.out.println("Total data rows found in table:"+ (allRows.size()-1)); System.out.println("====================================================================="); // Find the number of columns in each row System.out.println("Retrieving total number of columns for each row:"); for(int i=2;i<=allRows.size();i++) { List<WebElement> allColumnsInRow=driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td")); System.out.println("Number of columns in "+(i-1)+" data row is:"+allColumnsInRow.size()); } System.out.println("=================================="); //Print each row and columns from web table System.out.println("Printing all column value: "); for(int i=2;i<=allRows.size();i++) { List<WebElement> allColumnsInRow=driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td")); for(int j=0;j<allColumnsInRow.size();j++) { System.out.print(((WebElement) allColumnsInRow.get(j)).getText()+" "); } System.out.println(); } System.out.println("=================================="); // List books name and price whose author is mukesh System.out.println("Way 1: Books written by Mukesh are below:"); for(int i=2;i<=allRows.size();i++) { WebElement authorColumn=driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td[2]")); if(authorColumn.getText().toLowerCase().equalsIgnoreCase("Mukesh")) { WebElement bookNameColumns=driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td[1]")); System.out.println(bookNameColumns.getText()); } } System.out.println("=================================="); // Another shortcut way System.out.println("Way 2: Books written by Mukesh are below:"); List<WebElement> allColumnsInRow=driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr/td[text()='Mukesh']/../td[1]")); for(WebElement e: allColumnsInRow) { System.out.println(e.getText()); } // Print book name whose price is greater than and equal to 1000 System.out.println("=================================="); System.out.println("Books with price greater than and equal to 1000 are below:"); for(int i=2;i<=allRows.size();i++) { WebElement priceColumn=driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td[4]")); if(Integer.parseInt(priceColumn.getText())>=1000) { WebElement bookName=driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+i+"]/td[1]")); System.out.println(bookName.getText()); } } System.out.println("=================================="); // How to print data from the last row System.out.println("Directly printing column values of last row of table: "); List<WebElement> columnOfLastRow= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr[last()]/td")); for(WebElement e:columnOfLastRow) { System.out.println(e.getText()); } System.out.println("=================================="); // find sum of cost of all books listed List<WebElement> costColumns= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr/td[4]")); int sum_price=0; for(WebElement e:costColumns) { sum_price= sum_price+Integer.parseInt(e.getText()); } System.out.println("total price: "+sum_price); System.out.println("=================================="); // Retrieve cell value by providing row and column number WebElement colValue= driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr[2]/td[3]")); System.out.println("Cell Value : "+colValue.getText()); System.out.println("=================================="); System.out.println("Cell value using custom method: "+HandlingWebTable.getColValue(2, 3, driver)); // Printing column index based on the column name List<WebElement> allHeadersOfTable2= driver.findElements(By.xpath("//table[@name='BookTable']/tbody/tr[1]/th")); for(int k=0;k<allHeadersOfTable2.size();k++) { if(allHeadersOfTable2.get(k).getText().equalsIgnoreCase("price")) { System.out.println("Column index of Price column is: "+(k+1)); } } driver.quit(); } public static String getColValue(int row, int col, WebDriver driver) { WebElement colValue= driver.findElement(By.xpath("//table[@name='BookTable']/tbody/tr["+row+"]/td["+col+"]")); return colValue.getText(); } }
Output:
Printing all header of table assuming first row as header: Headers in table are below: Total headers found: 4 BookName Author Subject Price ===================================================================== Printing all header of table without information of row header Headers in table are below: Total headers found: 4 BookName Author Subject Price ===================================================================== Retrieving total number of data rows: Total data rows found in table:6 ===================================================================== Retrieving total number of columns for each row: Number of columns in 1 data row is:4 Number of columns in 2 data row is:4 Number of columns in 3 data row is:4 Number of columns in 4 data row is:4 Number of columns in 5 data row is:4 Number of columns in 6 data row is:4 ===================================================================== Printing all column value: Learn Selenium Amit Selenium 300 Learn Java Mukesh Java 500 Learn JS Animesh Javascript 300 Master In Selenium Mukesh Selenium 3000 Master In Java Amod JAVA 2000 Master In JS Amit Javascript 1000 ===================================================================== Way 1: Books written by Mukesh are below: Learn Java Master In Selenium ===================================================================== Way 2: Books written by Mukesh are below: Learn Java Master In Selenium ======================================================================== Books with price greater than and equal to 1000 are below: Master In Selenium Master In Java Master In JS ======================================================================== Directly printing column values of last row of table: Master In JS Amit Javascript 1000 ======================================================================== total price: 7100 ======================================================================== Cell Value : Selenium ======================================================================== Cell value using custom method: Selenium Column index of Price column is: 4