How to access web table element in selenium web driver
There are 2 types of HTML table possible in the web.
- Static web table.
- Dynamic web table.
Static web table: Normally static tables are static in nature, means a number of column and row is fixed, it will never increase in runtime and data inside the each cell is also fixed.
Dynamic web table: It is just opposite of static web table, here row, column and cell data could be not fixed or we can say dynamic. It will change at runtime.
We need to follow few steps to retrieve data from web table
- We need to uniquely identify table object.
- Count number of rows present in the table.
- Count number of column present in each row.
- Get the value from each cell.
Step 1. We need to uniquely identify table object
Now we can start with the below table. We need to identify the web table uniquely.
Here we can see there an id for that highlighted table. The id is “ customers “. We know how to identify the web element using XPath or other selenium locators, you can refer my previous post also.
XPath for this table object
//*[@id="customers"]
Java code
driver.findelement(By.xapth(“//*[@id="customers"]”);
Step 2: Count Number of rows present in the table.
In HTML table row denoted as <tr>. So we need to count the number of <tr> present under the table.
We can directly count the number of rows is available on the table.
XPath for row count
//*[@id='customers']/child::*/child::tr
Above XPath will return 7 element
Java code
int rowCount = driver.findElements(By.xpath("//*[@id='customers']/child::*/child::tr")).size()
Step 3: Count Number of column present in each row.
Now we need to iterate each row and find out how many columns are there for that row.
Xpath for column count for first row (except header)
//*[@id='customers']/child::*/child::tr[1]/child::td
Above XPath will return 3 <td> tag
Java code
int columnCount = driver.findElements(By.xpath//[@id='customers']/child::*/child::tr[1]/child::td")).size()
Step 4: Get the value from each cell.
Java code
driver.findElement(By.xpath("//*[@id='customers']/child::*/child::tr["+row+"]/child::td["+column+"]")); element.getText()
Complete java code to iterate each row and column and print the value
public static void main(String argc[]){
System.setProperty("webdriver.chrome.driver","D:/workspace/TestProject/src/chromedriver.exe");
driver = new ChromeDriver() ;
driver.get("https://www.w3schools.com/html/html_tables.asp");
int rowCount = driver.findElements(By.xpath("//*[@id='customers']/child::*/child::tr")).size();
for (int i=1;i<=rowCount;i++){
int columnCount = driver.findElements(By.xpath("//*[@id='customers']/child::*/child::tr["+i+"]/child::td")).size();
for(int j=1;j<=columnCount;j++){
WebElement element = driver.findElement(By.xpath("//*[@id='customers']/child::*/child::tr["+i+"]/child::td["+j+"]"));
System.out.println(element.getText()+ " ");
}
System.out.println();
}
driver.quit();
}