Count the number of elements are matching with for the given xpath expression

31,006

Solution 1

Try this code:

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

The iCount has the number of elements having the same xpath value.

Solution 2

Another option If you are basing your requirements strictly on the need to use Selenium, you might be able to do something like this using WebElements and getting 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 returning the size of the returned list; if that's all you really want to get from it...

int mySize=myListToCheck.size()

I believe once you have an established WebElements list, you can also use iterators to go over that list. Helpful, I dunno... just providing another way to get to the same end-game.

Share:
31,006
Lingaraj R M
Author by

Lingaraj R M

Updated on August 10, 2022

Comments

  • Lingaraj R M
    Lingaraj R M almost 2 years

    How to count the number of elements are matching with for the given xpath expression

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

    all i need is the count.

  • Someone
    Someone almost 11 years
    I don't think this works as I have been trying to use this already unsuccessfully.
  • Jens Erat
    Jens Erat almost 11 years
    Since then I learned Selenium is not able to return the count(...) value. Edited but kept the answer for reference.
  • Someone
    Someone almost 11 years
    When you say "Other tools" what tools are you referring to? I ask as over the past 2 years I have been developing a browser game bot and have used so many different tools non of which managed to "mimic" a human the way Selenium Webdriver can.
  • Jens Erat
    Jens Erat almost 11 years
    There are several dozens of XPath processors. But I do not know about another one with similar features like Selenium.