samxli
samxli

Reputation: 1596

How to get the number of elements found using Selenium WebDriver with Python?

I looked at the documentation located here, but couldn't find an answer.

I want to get an element by class name or xpath and return the number of instances. There seems to be no available function in Python, such as get_xpath_count().

Any ideas on how to achieve this?

Upvotes: 6

Views: 112407

Answers (7)

Sam
Sam

Reputation: 2437

Try driver.find_elements_by_xpath and count the number of returned elements.

Upvotes: 12

mamal
mamal

Reputation: 1986

use this :

count_elemnts = len(driver.find_elements_by_...('name or class or id or xpath'))

elements (with an s) and not element

Upvotes: 1

Peter Graham
Peter Graham

Reputation: 2575

In python

element.find_elements()

will return all surface children Web Elements

Upvotes: 1

Ripon Al Wasim
Ripon Al Wasim

Reputation: 37756

In java, the following could work:

int xpathCount= driver.findElements(By.xpath("//div[@id='billingProfiles']/div[@class='cardContainer']")).size();

OR,

List<WebElement> xpath = driver.findElements(By.xpath("//div[@id='billingProfiles']/div[@class='cardContainer']"));
int xpathCount = xpath.size();
System.out.println("Total xpath: " + xpathCount);

For counting the total links in a page:
Way1:

List<WebElement> totalLinks = driver.findElements(By.tagName("a"));
int totalLinkSize = totalLinks.size();
System.out.println("Total Links by Way1 : " + totalLinkSize);

Way 2:

int totalLinkSize2 = driver.findElements(By.xpath("//a")).size();
System.out.println("Total Links by Way2 : " + totalLinkSize2);

Upvotes: 3

Nima Soroush
Nima Soroush

Reputation: 12814

You Can simply use len() function:

len(driver.find_elements_by_xpath('//a'))

Upvotes: 10

vlad
vlad

Reputation: 1

You can use 'assertXpathCount' command available in Selenium

Upvotes: -1

Pravesh
Pravesh

Reputation: 1

public static IWebDriver driver = null;

public static IList<IWebElement> elements;

// List count return total number of element

elements = driver.FindElements(By.XPath("//a"));

int intLinkCount = elements.Count;

Upvotes: 0

Related Questions