Search code examples
javaseleniumxpathselenium-webdriverwebdriver

Why is this WebElement not returning the full xpath?


I have several WebElements such that executing the following

List<WebElement> customers = driver.findElements(By.xpath("//div[@id='Customers']/table/tbody/tr"));
System.out.println(customers.size());

would print 5.

So then why does the following code

List<WebElement> customers = driver.findElements(By.xpath("//div[@id='Customers']/table/tbody/tr"));

for (WebElement customer : customers) {
    if (customer.getText().equals("SQA")) {
        WebElement test = customer;
        System.out.println(test);
        break;
    }
}

print xpath: //div[@id='Customers']/table/tbody/tr and fail to actually include the specific index of the path? The above xpath is absolutely useless; I'm expecting the location of where SQA was found.

xpath: //div[@id='Customers']/table/tbody/tr[4]


Solution

  • I think it just prints the locator used to find the element. If you want the index, just change your code to

    List<WebElement> customers = driver.findElements(By.xpath("//div[@id='Customers']/table/tbody/tr"));
    for (int i = 0; i < customers.size(); i++)
    {
        if (customers.get(i).getText().equals("SQA"))
        {
            System.out.println(i);
            break;
        }
    }