如何计算给定 xpath 表达式匹配的元素数量
xpath: driver.findElement(By.xpath("//div[contains(@id,'richedittext_instance')]"))
我需要的只是计数。
试试这个代码:
//Assume driver is intialized properly.
int iCount = 0;
iCount = driver.findElements(By.xpath("Xpath Value")).size());
iCount
具有相同 xpath
值的元素数量。
另一种选择 如果您的要求严格基于使用 Selenium 的需要,您也许可以使用 WebElements 执行类似的操作并获取返回列表的大小:
List<WebElement> myListToCheck=currentDriver.findElements(By.xpath("somePath"));
if(myListToCheck.size()>0){
//do this
}else{
//do something else
}
或者只是简单地返回返回列表的大小;如果这就是你真正想从中得到的一切......
int mySize=myListToCheck.size()
我相信一旦您建立了 WebElements 列表,您还可以使用迭代器来遍历该列表。 有帮助,我不知道......只是提供另一种方式来达到相同的结局。
在 Selenium 中不起作用,它只允许从 XPath 返回节点,而不是像
count(...)
返回的数字这样的基元。仅供参考,对于提供更完整 XPath API 的大多数其他工具都有效。
您应该只从查询中返回尽可能少的数据。
count(//div[contains(@id,'richedittext_instance')])
计算 within XPath 中的结果数量,因此速度更快,因为不必将所有元素从 XPath 引擎传递到 Selenium。
我无法帮助你如何从硒中获取这个 n
int
,但这应该很容易。
执行以下操作:
from selenium.webdriver.common.by import By
elements = driver.find_elements(By.XPATH, "Your_XPath")
这将输出一个
selenium.webdriver.firefox.webelement.FirefoxWebElement
列表(在我的 Firefox 浏览器中)。
最后,找出列表的长度:
len(elements)
NB.:请注意,我写的是
find_elements()
(复数)而不是 find_element()
。两者是不同的。 find_element()
仅返回第一个匹配的Web元素,但要查找所有匹配的Web元素的列表,我们必须使用find_elements()
。
我想打印共享相同 xpath 的元素数量。使用下面的代码 - 我可以打印控制台和范围报告中的元素数量。
enter code here
List<WebElement> noOfTiles = baseTestSuite.getDriver() .findElements(By.xpath("//android.widget.RelativeLayout[contains(@resource-id,'pf_tile_outer')]")); if(noOfTiles.size()>0){ System.out.println("No. of tiles on Add cash page are:"+" "+noOfTiles.size()); int numberOfTiles = noOfTiles.size(); // converting the int to String because getLogger is not to print the integer. String s=String.valueOf(numberOfTiles); getLogger().log(LogStatus.PASS, s); }