Search code examples
javaseleniumxpathhtml-tablewebdriver

Getting rows from a table by index in special cases using Selenium with Java


We have a table where the first row in the tbody actually describes the headers rather than the headers being in a thead. So I have something like the following to get the headers.

 @FindBy(xpath = "//table/tbody/tr[1]/th")
 private List<WebElement> headerRows.

I would like to make something similar to get the detail rows (starting from row 2). If I do

 @FindBy(xpath = "//table/tbody/tr")
 private List<WebElement> detailRows;

This will also get the header row. I would like to exclude index 1. I tried this:

 @FindBy(xpath="//table/tbody/tr[!1]") and @FindBy(xpath="//table/tbody/tr[not(1)]")

but those didn't work? Any suggestions? I can do it with code and find and skip the first row when reading in a loop if necessary:

 @FindBy(xpath="//table/tbody/tr")
 private WebElement rows;

 for (int i = 1; i rows.size(); i++) {
      WebElement row = rows.get(i);
 }    

but that does not seem elegant. Is that the best way?


Solution

  • If you want to exclude header row you can use below xpath, which will ignore th column.

    //table/tbody/tr[not(th)]
    

    your code will be

    @FindBy(xpath = "//table/tbody/tr[not(th)]")
     private List<WebElement> detailRows;