代码之家  ›  专栏  ›  技术社区  ›  Archit Arora

使用Groovy脚本在许多HTML元素中检查相同的属性

  •  2
  • Archit Arora  · 技术社区  · 7 年前

    嗨,我是Groovy的新手。

    我想深入到DOM结构中,检索一组元素,并检查这些元素是否具有特定的属性。

    assert $("#myID > div > div > div > p > a > span").attr("class").contains("my-class")
    

    $("#myID > div > div > div > p > a > span") 返回3个span元素,因此上述语句失败并引发错误-

    geb.error.SingleElementNavigatorOnlyMethodException: Method getAttribute(java.lang.String) can only be called on single element navigators but it was called on a navigator with size 3. Please use the spread operator to call this method on all elements of this navigator or change the selector used to create this navigator to only match a single element.
    

    my-class 属性?

    提前谢谢!

    3 回复  |  直到 7 年前
        1
  •  2
  •   rdmueller    7 年前

    因此,由于使用Groovy,因此可以使用foreach来迭代元素:

    def containsAttr = true
    $("#myID > div > div > div > p > a > span").each { element ->
        if (! element.attr("class").contains("my-class")) {
            containsAttr = false
        }
    }
    assert containsAttr == true
    

    each 循环显示了最好的方法。

    http://docs.groovy-lang.org/next/html/documentation/working-with-collections.html 有关集合的详细信息。

    PS:我给出的代码的一个缺点是,当power断言失败时,它不会显示太多mich信息。

        2
  •  1
  •   Louys Patrice Bessette    7 年前

    在jQuery中,要循环遍历元素colection, .each() 是有用的。可能是:

    $("#myID > div > div > div > p > a > span").each(function(){
      if($(this).hasClass("my-class")){
        console.log("Found one!");
      }
    });
    

    $("#myID").find(".my-class")
    

    它将针对您要查找的元素。

    .contains() 在类属性中查找类是不好的。所以你犯的错误可能是因为误用。

    免责声明:我对Groovy一无所知,所以我不确定您需要什么。

        3
  •  0
  •   Aditya Sharma    7 年前

    你也可以检查一下

    assert $("#myID > div > div > div > p > a > span").length === $("#myID > div > div > div > p > a > span.my-class").length
    

    类似地,如果属性选择器不总是类,则可以使用它。