Tuesday, 4 August 2015

How to handle dynamic web tables/HTML tables in Selenium webdriver using java?.

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 Dynamictablehandler {

    public static void main(String[] a) throws InterruptedException {
        // Initialize Web driver   
        WebDriver driver = new FirefoxDriver();
        //Maximize browser window  
        driver.manage().window().maximize();
        //Go to Page   
        driver.get("file:///F:/table.html");
        //get the entire html table and store this in a variable
WebElement table = driver.findElement(By.xpath("html/body/table/tbody"));
        //Get all the rows
List<webelement> rows = table.findElements(By.tagName("tr"));

        for (int r = 0; r < rows.size(); r++) {
            //Get all the columns in every row
List<webelement> columns = rows.get(r).findElements(By.tagName("td"));
            for (int col = 0; col < columns.size(); col++) {
System.out.print(columns.get(col).getText().trim() + "   ");
            }
            System.out.println();
        }
        driver.quit();
    }

}

No comments:

Post a Comment