【问题标题】:Check for child tag inside parent tag检查父标签内的子标签
【发布时间】:2016-07-04 13:28:09
【问题描述】:

是否可以知道父级是否包含具有特定类名的子级。 示例代码

<div id="parent_tag">
   <div id="div1">
      <span>Title 1</span>
   </div>
   <div id="div2">
      <b>Title 2</b>
   </div>
   <div id="div3">
      <span>Title 3</span>
   </div>
</div>

我尝试仅使用 Title 3 访问“span 标签”。我知道我可以通过指定 id 来做到这一点。但是如果我想要一般地(即所有元素)怎么办。所以我的第一种方法应该是“我将在 div 中查找 span 标签”。但我不知道该怎么做?请帮忙。

【问题讨论】:

  • 检查我的答案,但实际上我不确定我是否正确理解你所说的child with specific class name,但是在提供的HTML 中没有指定类的元素......

标签: selenium webdriver


【解决方案1】:

试试XPath:

//div/span[text()="Title 3"]

【讨论】:

    【解决方案2】:

    在div3中使用jquery选择器选择span:

    $("#div3 span")
    

    或者特别是div3中的第一个span元素:

    $("#div3 span:first")
    

    【讨论】:

      【解决方案3】:

      这是获得所需的想法

          // Get Parent Element
          WebElement parent = driver.findElement(By
                  .xpath("//div[@id='parent_tag']"));
      
          // Get All children elements of the parent element
          List<WebElement> children = parent.findElements(By.xpath("//*"));
      
          // Init some based param for next usage
          boolean checkClass = false;
          String expectedClass = "Expected_Class";
      
          // Fetch each child element and check whether its text contains expected string.
          for (WebElement child : children) {       
              if (child.getAttribute("class").contains(expectedClass)) {
                  checkClass = true;
              }
          }
      
          if (checkClass) {
              System.out
                      .println("We have at least one child has expected class: "
                              + expectedClass);
          }
          else System.out.println("We don't have any child has expected class: "
                              + expectedClass);
      

      如果你想检查文本,我们可以做

          if (child.getText().contains(expectedText)) {        
                  checkResult = true;
              }
          }
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-06
        • 2021-10-03
        • 1970-01-01
        相关资源
        最近更新 更多