简体   繁体   中英

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?

尝试driver.find_elements_by_xpath并计算返回元素的数量。

您可以简单地使用len()函数:

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

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);
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;

您可以使用 Selenium 中可用的“assertXpathCount”命令

In python

element.find_elements()

will return all surface children Web Elements

use this :

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

elements (with an s) and not element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM