Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

selenium

xpath

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.

like image 677
Lingaraj R M Avatar asked Feb 08 '13 06:02

Lingaraj R M


2 Answers

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.

like image 152
Manigandan Avatar answered Oct 20 '22 17:10

Manigandan


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.

like image 1
ronsky Avatar answered Oct 20 '22 17:10

ronsky