Search code examples
javaselenium-webdrivertestngtestng-eclipse

How to get elements from table in Selenium Web Driver JAVA


I am trying to Identify Elements of the page. I have table and there is lot of rows with multiple Inputs. How to access Input from table rows?

This is my java class

public class Setting extends Page {

    /**Identify Elements of the page*/

    @FindBy(id="table-settings")

    private WebElement Table;

    //Constructor
    public Setting()
    {
        /**Initialize PageFactory WebElements*/
        PageFactory.initElements(driver, this);
    }   

}

Solution

  • Refer below code, make changes accordingly, Let me know if you find any hurdle in it

    @Test
    public void test() {
        WebElement Webtable=driver.findElement(By.id("TableID")); // Replace TableID with Actual Table ID or Xpath
    
        List<WebElement> TotalRowCount=Webtable.findElements(By.xpath("//*[@id='TableID']/tbody/tr"));
    
        System.out.println("No. of Rows in the WebTable: "+TotalRowCount.size());
        // Now we will Iterate the Table and print the Values   
    
        int RowIndex=1;
    
        for(WebElement rowElement:TotalRowCount)
        {
            List<WebElement> TotalColumnCount=rowElement.findElements(By.xpath("td"));
            int ColumnIndex=1;
    
            for(WebElement colElement:TotalColumnCount)
            {
                System.out.println("Row "+RowIndex+" Column "+ColumnIndex+" Data "+colElement.getText());
                ColumnIndex=ColumnIndex+1;
            }
            RowIndex=RowIndex+1;
        }
    }