如何使用 xpath 定位动态元素(ends-with 函数不起作用)

Nis*_*pan 5 selenium xpath

我已经使用了结束函数作为 (By.xpath("//input[ends-with(@id,'_PHONE$']"));

但它没有用

JRo*_*ite 8

ends-with函数是 XPath 2.0 的一部分,但浏览器通常只支持 1.0。

因此,如果您严格想要获取以特定模式结尾的所有元素,您可以获取包含该模式的所有元素(使用contains()函数),然后使用 Java 的方法严格检查id(获取属性值.getAttribute("id"))的后缀.endsWith().

或者

您可以使用string-lengthfunction、substringfunction 和 equals 来获取此 XPath:

"//input[substring(@id, string-length(@id) - string-length('_PHONE$1') +1) = '_PHONE$1']"
Run Code Online (Sandbox Code Playgroud)


Pra*_*eek 0

您的 ID 以 _PHONE$1 结尾,而不是 _PHONE$。1注意最后有一个。

(By.xpath("//input[ends-with(@id,'_PHONE$1']"));
Run Code Online (Sandbox Code Playgroud)

如果您仍然不想匹配该 1,请使用contains.

By.xpath("//input[contains(@id,'_PHONE$1']"));
Run Code Online (Sandbox Code Playgroud)