首页 > 解决方案 > 使用 Groovy 脚本检查多个 HTML 元素中的相同属性

问题描述

嗨,我是 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属性?

提前致谢!

标签: jquerygroovygeb

解决方案


因此,由于您使用 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

重要的是您将 $()-Selection 元素识别为集合。当您在 groovy 知识方面取得进展时,您会发现更通用的方法来遍历集合,但我认为目前,each循环最好地展示了它是如何完成的。

有关集合的更多详细信息,请参阅http://docs.groovy-lang.org/next/html/documentation/working-with-collections.html

PS:我给出的代码的一个缺点是电源断言在失败时不会透露太多信息。


推荐阅读