Wednesday, February 22, 2017

How To Handle Dynamic Web Table In Selenium WebDriver

In this selenium webdriver post, we will learn how to handle dynamic web table. There might occur some scenarios where every time a page loads with different number of rows and columns or different columns for each row.

For that, we have to put two for loops,
1. first loop will iterate all the rows and
2. second loop inside it will iterate the columns of each row

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.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class DynamicTable {
WebDriver driver = new FirefoxDriver();
public void setup() throws Exception {
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
public void tearDown() throws Exception {
public void Handle_Dynamic_Webtable() {
//To locate table.
WebElement mytable = driver.findElement(By.xpath(".//*[@id='post-body-8228718889842861683']/div[1]/table/tbody"));
//To locate rows of table.
List rows_table = mytable.findElements(By.tagName("tr"));
//To calculate no of rows In table.
int rows_count = rows_table.size();
//Loop will execute till the last row of table.
for (int row=0; row
//To locate columns(cells) of that specific row.
List Columns_row = rows_table.get(row).findElements(By.tagName("td"));
//To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row "+row+" are "+columns_count);
//Loop will execute till the last cell of that specific row.
for (int column=0; column
//To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number "+row+" and column number "+column+" Is "+celtext);

Feel free to ask queries. Happy Coding :)

Vaneesh Behl