【问题标题】:How to count HTML child tag in Selenium WebDriver using Java如何使用 Java 计算 Selenium WebDriver 中的 HTML 子标签
【发布时间】:2013-12-31 10:43:25
【问题描述】:

在 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>

我想数一下product_row div下有多少个form标签? 谢谢

【问题讨论】:

  • 我可能会使用 xpath 表达式://xpath-to-element[count(childExpression)]
  • 其实:count(//div[@class='product_row']/form[@class='product_container']) 比较具体
  • @DanielChapman:这不会产生任何元素。 Selenium 只能处理实际元素,不能处理 XPath 的文本或计数等。
  • 真的吗?这是很好的信息。今晚我会验证它。
  • 感谢大家帮助我。 @User1177636 您的脚本一次性工作并没有尝试其他人,但现在会给其他人一个机会 - 再次感谢您的所有帮助。

标签: java html selenium selenium-webdriver


【解决方案1】:

先找到父div,然后定位所有目标元素,再统计。

List<WebElement> forms = driver.findElements(By.cssSelector(".product_row form"));
int count = forms.size();

【讨论】:

    【解决方案2】:

    这里有两种解决方案:

    你可以通过 xpath 选择

    driver.findElements(By.xpath("//div[@class='product_row']/form"))
    

    或者您可以通过 user1177636

    中提到的 CSS 查询进行选择
    driver.findElements(By.cssSelector(".product_row>form"))
    

    【讨论】:

    • @user1177636 它们是一个问题的两种解决方案。
    • 我们不应挑剔answersolution的定义之间的区别,而应关注手头的问题。
    【解决方案3】:

    您可以使用以下语句找到元素的大小:

    System.out.println(driver.findElements(By.xpath("//div[@class='product_row']/form")).size());
    

    其中.findElements方法返回计数值,该页面中的所有元素由xpath //div[@class='product_row']/form组成

    在您的情况下,它将返回“3”作为结果

    【讨论】:

      【解决方案4】:

      一般来说,我会使用某种方法来查找我想要的所有元素,或者使用 xpath 或 css 选择器,然后只计算返回了多少结果。

      【讨论】:

        【解决方案5】:

        每个元素都有一个名为 childElementCount 的属性。 您可以使用 WebElement.getAttribute() 函数来获取即时值。

        WebElement element = driver.findElement(By.className("product_row"));
        int numberOfChilds = Integer.parseInt(element.getAttribute("childElementCount"));
        

        因为 getAttribute() 返回一个字符串,我们必须将它转换为一个 int。

        【讨论】:

          猜你喜欢
          • 2016-11-15
          • 2012-08-24
          • 1970-01-01
          • 2017-05-09
          • 2013-05-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多