Count the number of elements matching the given xpath expression

How to count the number of elements matching a given xpath expression

xpath: driver.findElement(By.xpath("//div[contains(@id,'richedittext_instance')]")) 

I only need an account.

+8
xpath selenium
source share
3 answers

Try this code:

 //Assume driver is intialized properly. int iCount = 0; iCount = driver.findElements(By.xpath("Xpath Value")).size()); 

iCount has the number of elements that have the same xpath value.

+13
source share

Another option If you base your requirements strictly on the need to use Selenium, you can do something similar using WebElements and get the size of the returned list:

 List<WebElement> myListToCheck=currentDriver.findElements(By.xpath("somePath")); if(myListToCheck.size()>0){ //do this }else{ //do something else } 

Or just simply return the size of the returned list; if that's all you really want to get from him ...

 int mySize=myListToCheck.size() 

I believe that if you have an installed list of WebElements, you can also use iterators to navigate this list. Useful, I don’t know ... just provide another way to get to the same final game.

+1
source share

Does not work in Selenium, which allows you to return nodes from XPath, not primitives, such as the number returned by count(...) . Saved for reference and valid for most other tools offering a more comprehensive XPath API.

You should return only the smallest possible amount of data from the query. count(//div[contains(@id,'richedittext_instance')]) counts the number of results in XPath and therefore faster since all elements should not be passed from the XPath mechanism to Selenium.

I cannot help you get this as n int from selenium, but it should be easy.

0
source share

All Articles