如何使用 xpath 在 span 中查找元素

How to find an element in the span with xpath

我在使用 xpath 查找元素时遇到问题。实际上有两个要素。例如 bundle1bundle11 它将附加(数字资源)数字是动态的。

在代码中我使用了下面的代码,但是 bundle1bundle11 都得到了。在代码 elementName 中,如果使用 bundle1,则 bundle1bundle11 都将通过 Xpathtext() 将是 bundle11(33 个资源)或 bundle11(33 个资源)

return this.viewPortElement.findElement(
By.xpath(".//table//td/div/div//span[span[startswith(text(),'"+elementName+"')]]"));        }

有什么方法可以定位元素吗?在网页中对应的html如下

<span title="bundle11 (33 Resources)">bundle1 (33 Resources)</span>

<span title="bundle11 (33 Resources)">bundle11 (33 Resources)</span>

一种可能的方法是在数字后附加白色 space :

return this.viewPortElement
           .findElement(
                By.xpath(".//table//td/div/div//span[span[startswith(text(),'"
                            +elementName
                            +" ')]]"
                            //^notice white space added here
                        )); 

这样,给定 elementName 变量赋值 1 例如,您可以只匹配 bundle1 而不会无意中匹配 bundle11.