在 Selenium 中通过 xpath 查找包含引号的文本

Find texts that contains quotation marks by xpath in Selenium

我刚在 Selenium 中遇到错误(Java):

Unable to locate an element with the xpath expression //*[contains(.,'The field SomeField must be a string or array type with a maximum length of '60'.')]

显然,有两个 ' 破坏了表达式。所以我把代码从

WebElement elem = findElement(By.xpath("//*[contains(.,'" + arg + "')]"));

WebElement elem = findElement(By.xpath("//*[contains(.,'" + arg.toString().replace("'", "\'") + "')]"));
WebElement elem = findElement(By.xpath("//*[contains(.,'" + arg.toString().replace("'", "\'") + "')]"));
WebElement elem = findElement(By.xpath("//*[contains(.,'" + arg.toString().replace("'", "\\'") + "')]"));

None 他们成功了。现在我暂时通过这样做来解决它:

WebElement elem = findElement(By.xpath("//*[contains(.,\"" + arg + "\"')]"));

但如果 arg 中包含 ",错误将再次出现。

有人知道怎么做吗?感谢您的帮助。

使用 String.format 通过以下方式构建您的 xpath:

WebElement elem = findElement(By.xpath(String.format("//*[contains(.,\"%s\")]", arg)));

有关 String.format 的更多信息,请查看它的 documentation。 可以找到格式参数 here.


arg 只能包含 '

WebElement elem = findElement(By.xpath(String.format("//*[contains(.,\"%s\")]", arg)));

arg 只能包含 "

WebElement elem = findElement(By.xpath(String.format("//*[contains(.,'%s')]", arg)));

arg 可以同时包含 '"

arg.replace("\"", """); 转义 arg 中的所有 " 并像

一样构建你的 Xpath
WebElement elem = findElement(By.xpath(String.format("//*[contains(.,\"%s\")]", arg)));