Handling web tables in selenium

A basic web table will have these below components:
header, body and footer
Header cells- th
Body cells - td
Rows - tr
Header and footer are optional for a webtable.
Some of the webpages may or may not have header and footer,

if there is no thead, then header is absent and we can deal the table with the tbody only.
A basic webtable HTML looks like below:

Let's see the implementation:
package controls;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Table1 {

 public static void main(String[] args) {
 WebDriver driver = new FirefoxDriver();
 driver.get("http://www.qavalidation.com/p/demo.html");
 driver.manage().window().maximize();
 WebElement Table_1 = driver.findElement(By.id("table01"));
 List<webelement> Rows = Table_1.findElements(By.tagName("tr"));
 System.out.println("No. of rows: "+Rows.size());
 
 //to print all the values inside the table
 /*for(WebElement Row : Rows)
 {
  List<webelement> Cols = Row.findElements(By.tagName("td"));
  for(WebElement Cel : Cols)
  {
   System.out.print(Cel.getText()+" ");
  }
  System.out.println();
 }*/
 
 //Find a matching text in a table and perform some action
 mainloop:
 for(int i=0; i<Rows.size();i++)
 {
  List<webelement> Cols = Rows.get(i).findElements(By.tagName("td"));
  for(int j=0; j<Cols.size();j++)
  {
   if(Cols.get(j).getText().contains("TFS"))
   {
    Cols.get(0).findElement(By.tagName("input")).click();
    break mainloop;
   }
  } 
 }  
  }

}
Another way of working tables:
use of xpath: if we inspect webtable cells with the firebug on webpage, the xpath mostly remains same except the index of tr and td tag...
As you can see in above screenshot, item TFS is on 2nd row and 4th column...
so we can use 2 for loops to iterate the tr and td tags to get the cell values,
let's see
//Use xpath to print the table content
String cell=null;
  for(int i=0;i<Rows.size();i++)
     {
 List cols=Rows.get(i).findElements(By.tagName("td"));
 for(int j=0;j<cols.size();j++)
   {
     cell = driver.findElement(By.xpath(".//*[@id='table01']/tbody/tr["+i+"]/td["+j+"]")).getText();
     System.out.print(cell);
   }
   System.out.println();
     }

No comments:

Post a Comment