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



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

但它没有奏效

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

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

您可以使用string-length函数、substring函数和等于来获取此 XPath:

"//input[substring(@id, string-length(@id) - string-length('_PHONE$1') +1) = '_PHONE$1']"
driver.findElement(By.xpath("//id[contains(text(),'PHONE$')]"));

您也可以在XPath下面使用:-

//input[contains(@id,'PHONE$1')]

希望它能帮助你:)

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

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

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

By.xpath("//input[contains(@id,'_PHONE$1']"));

use 包含方法

By.xpath("//input[contains(text(), '_PHONE$']");

或使用等待显式方法

最新更新