如何使用 Java 在 Selenium WebDriver 中计算 HTML 子标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20553372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count HTML child tag in Selenium WebDriver using Java
提问by Onu
In Selenium JAVA WebDriver - How can I count child tags? Example:
在 Selenium JAVA WebDriver 中 - 如何计算子标签?例子:
<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 formtag are there under product_row div? Thanks
我想计算product_row div下有多少个表单标签?谢谢
回答by Yi Zeng
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();
回答by MxLDevs
In general, I would use some way to find all of the elements that I want, either using xpath or css selectors, and then just count how many results are returned.
通常,我会使用某种方法来查找我想要的所有元素,无论是使用 xpath 还是 css 选择器,然后只计算返回了多少结果。
回答by Michael
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"))
回答by Sravan
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”作为结果