Get value of aggregate xpath function in Selenium Java

67 Views Asked by At

I'm trying to get the index of a <tr> element based on the contents of its <td> elements in Selenium using xpath.

String xpath = "count(//tr[td[text()='Column Value A'] and td[text()='Column Value B']]/preceding-sibling::*)"
WebElement count = driver.findElement(By.xpath(xpath))

However, I'm getting this exception.

org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression count(//tr[td[text()='Column Value A'] and td[text()='Column Value B']]/preceding-sibling::*) because of the following error:
TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type.

Is there any way for Selenium to return the value of an aggregate xpath function?

Thanks in advance for your help!

1

There are 1 best solutions below

0
On

You XPATH seems to be wrong.

String xpath = "//tr[td[text()='Column Value A'] and td[text()='Column Value B']]/preceding-sibling::*"
WebElement count = driver.findElement(By.xpath(xpath))

Please check this out.
Reg your query

I'm trying to get the index of a element based on the contents of its elements in Selenium using xpath.

What I usually do is, maintain 3 different locators for header and row.

By dataRows = By.xpath("//tr[./td]");
By cellData = By.xpath("//td");
By tableHeaders = By.xpath("//tr/th");

If we want to check whether the first row contains the specified value, we need to call this method as:
int columnIndex = getColumnIndex(0,"Ahamed Abdul Rahman");

public int getColumnIndex(int rowIndex, String value) {
    List<WebElement> rowthElements = driver.findElements(dataRows).get(rowIndex).findElements(cellData);
    return IntStream.range(0, rowthElements.size())
            .filter(i -> rowthElements.get(i).getText().equals(value))
            .findFirst().orElse(-1);
}

This method returns the header name at that column's index:

public String getHeaderName(int columnIndex) {
    return driver.findElements(tableHeaders).get(columnIndex).getText();
}

Doing directly in Xpath may be possible but I found this easier for me.