在Selenium中通过xpath查找包含引号的文本 [英] Find texts that contains quotation marks by xpath in Selenium

查看:41
本文介绍了在Selenium中通过xpath查找包含引号的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just got an error in Selenium(Java):

无法使用 xpath 表达式定位元素//*[contains(.,'字段 SomeField 必须是字符串或数组类型最大长度为'60'.')]

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'.')]

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

Apparently, there are two ' which broke the expression. So I changed the code from

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 of them worked. Now I temporarily work it out by doing this:

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

但是如果 arg 中包含 " ,错误会回来.

But the bug will come back if the arg contains " in it.

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

Anyone knows how to do that? Thanks for your help.

推荐答案

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

Use String.format to build your xpath the following ways:

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

有关 String.format 的更多信息,请查看它的 文档.格式参数可以在这里找到.

For further information about String.format take a look at it's documentation. The format arguments can be found here.

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 一样

arg can contain both ' and "

Escape all " in arg with arg.replace("\"", """); and build your Xpath like

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

这篇关于在Selenium中通过xpath查找包含引号的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆