Home > Back-end >  How to validate column position in webtable using Selenium Java?
How to validate column position in webtable using Selenium Java?

Time:01-21

I got 5 columns in a table: Name, Birth year, Gender, Occupation and Salary.

Task is to check whether occupation column title is located at 2nd place from the right side.

public void positionofOccupation() {
        List < WebElement > ch = driver.findElements(By.xpath("//button[@class='header']"));
        for (int i = ch.size(); i > 0; i--) {
            WebElement ch1 = driver.findElement(By.xpath("(//button[@class='header'])["   i   "]");
                    if (ch1.getText().trim().contains("Occupation")) {
                        System.out.println("Occupation position is at "   i   " column);
                        }
                        else {
                            System.out.println("Occupation position is wrong and is at "   i   " column);
                            }
                        }
                    }

It's printing me a 4 instead of 2 when that "if" condition is true. I need to print 2 because test case is about 2nd position not 4th position.

CodePudding user response:

You can use this code snippet to achieve the same

List<WebElement> ch = driver.findElements(By.xpath("//button[@class='header']"));
int size = ch.size();
for (int i = size-1; i >= 0; i--) {
    WebElement ch1 = ch.get(i);
    if (ch1.getText().trim().contains("Occupation")) {
        System.out.println("Occupation position is at "   (size-i)   " column from the right side.");
        break;
    }
}

As for as I know this will correctly print the position of the Occupation column as 2, because it is the second column from the right side

  • Related