Zack
Zack

Reputation: 2208

How to get count of Selenium XPath results

As of now I am getting the count of the number of matching results using listChanges.size() . How do I directly get the count without loading getChanges in the list?

By getChanges = By.xpath("//td[contains(@class,'blob-code blob-code-addition') or contains(@class,'blob-code blob-code-deletion')]");

List<WebElement> listChanges = driver.findElements(getChanges);

I found this(Count function in XPath) and I tried the below which does not work!

Integer getCount = By.xpath(count("//td[contains(@class,'blob-code blob-code-addition') or contains(@class,'blob-code blob-code-deletion')]"));

Looks like I have to do something like this.

Integer getCount = By.xpath("count(//td[contains(@class,'blob-code blob-code-addition') or contains(@class,'blob-code blob-code-deletion')])");

But the right hand side returns an object of type By

Upvotes: 2

Views: 5949

Answers (2)

Saifur
Saifur

Reputation: 16201

As alex says, size() is the way to go. However I do have another suggestion for you. Even though the proper way to find the element counts is to use WebDriver api with findElements() as per my knowledge. Another way is to execute javascript by using executeScript() and with proper script. I am not sure if javascript and xpath can be mixed together to accomplish this since xpath execution through javascript is not multi-browser right now. See this. However, I do think using cssSelector with javascript can make it lot easier to accomplish. See the following code :

String cssQuery = ".blob-code-addition, .blob-code-deletion";
String script = "return document.querySelectorAll('" + cssQuery + "').length;";
Object count = ((JavascriptExecutor)driver).executeScript(script);

System.out.println(count);

Print

26

Upvotes: 2

alecxe
alecxe

Reputation: 474131

You cannot get the count using XPath, because an xpath expression in selenium has to correspond to an actual element on a page.

The way you are doing it via findElements() + size() is how you have to count elements using the selenium webdriver.

Upvotes: 2

Related Questions