Selenium WebDriver - Handle Dynamic Web Table


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


public class DynamicTable {

  WebDriver driver = new FirefoxDriver();
  
  @BeforeTest
  public void setup() throws Exception {
  driver.manage().window().maximize();

 
 driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

  driver.get("https://www.techlistic.com/p/sample-table.html");
  }

  @AfterTest
  public void tearDown() throws Exception {
  driver.quit();
  }

  @Test
  public void test_Dynamic_Webtable() {
  // Locate table
  WebElement mytable = driver.findElement(By.xpath(".//*[@id='post']/div[1]/table/tbody"));

  // Locate rows of table and save locators of each row in a list
  List rows_table = mytable.findElements(By.tagName("tr"));

  // Get 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<=rows_count; row++) 
  {
    // locate columns(cells) of that specific row.
    List Columns_row = rows_table.get(row).findElements(By.tagName("td"));

    // Get 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<=columns_count; column++) {

  // 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 share your thoughts in comments or email me. Happy Coding :)

Author: Vaneesh Behl

Join Telegram channel of this blog at https://t.me/techlisticspace


Comments

Post a Comment

Popular Posts

Top 10 Demo Websites to Practice Selenium Webdriver Online

Selenium Essentials - How to become expert in Automation Testing?

Top 25 Must to know Selenium Webdriver Commands List

Selenium WebDriver - Browser and Navigation Commands

Selenium IDE - Sample Script With Most Commonly Used Commands