8protons
8protons

Reputation: 3979

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]

Upvotes: 0

Views: 51

Answers (2)

Mohammad Sumon
Mohammad Sumon

Reputation: 1

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

    for (int i = 0; i < customers.size(); i++) {
        WebElement customer = customers.get(i);
        if (customer.getText().equals("SQA")) {
            int index = i + 1; // XPath indices start at 1, not 0
            String xpath = "//div[@id='Customers']/table/tbody/tr[" + index + "]";
            System.out.println("XPath: " + xpath);
            break;
        }
    }

Upvotes: 0

JeffC
JeffC

Reputation: 25644

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;
    }
}

Upvotes: 2

Related Questions