[英]How to count HTML child tag in Selenium WebDriver using Java
In Selenium JAVA WebDriver - How can I count child tags?在 Selenium JAVA WebDriver 中 - 如何计算子标签? Example:
示例:
<div class="subcategory_container">
<div class="products_container">
<div class="product_row">
<form class="product_container">
<form class="product_container">
<form class="product_container">
</div>
</div>
</div>
I want to count how many form tag are there under product_row div ?我想计算product_row div下有多少个表单标签? Thanks
谢谢
You find the parent div first, then locate all target elements, then count them.你先找到父div,然后定位所有目标元素,然后统计它们。
List<WebElement> forms = driver.findElements(By.cssSelector(".product_row form"));
int count = forms.size();
Here are two solutions:这里有两个解决方案:
You could either select by xpath您可以通过 xpath 选择
driver.findElements(By.xpath("//div[@class='product_row']/form"))
or you could select by CSS query as mentioned by user1177636或者您可以通过user1177636提到的 CSS 查询进行选择
driver.findElements(By.cssSelector(".product_row>form"))
You can find the size of elements by using the following statement:您可以使用以下语句找到元素的大小:
System.out.println(driver.findElements(By.xpath("//div[@class='product_row']/form")).size());
Where .findElements
method returns count value that all elements in that a page consists with xpath //div[@class='product_row']/form
其中
.findElements
方法返回该页面中所有元素由 xpath //div[@class='product_row']/form
组成的计数值
In your case it will return "3" as result在您的情况下,结果将返回“3”
通常,我会使用某种方法来查找我想要的所有元素,无论是使用 xpath 还是 css 选择器,然后只计算返回了多少结果。
Every element has an attribute called childElementCount.每个元素都有一个名为 childElementCount 的属性。 You can use WebElement.getAttribute() function to get an immediate value.
您可以使用 WebElement.getAttribute() 函数来获取即时值。
WebElement element = driver.findElement(By.className("product_row"));
int numberOfChilds = Integer.parseInt(element.getAttribute("childElementCount"));
Because getAttribute() returns a String, we have to cast it to an int.因为 getAttribute() 返回一个 String,所以我们必须将它转换为一个 int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.