Find texts that contains quotation marks by xpath in Selenium

♀尐吖头ヾ 提交于 2021-02-19 06:28:21

问题


I just got an error in 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'.')]

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

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

to

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 + "\"')]"));

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

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


回答1:


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

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

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


arg can only contain '

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

arg can only contain "

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

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)));


来源:https://stackoverflow.com/questions/59287319/find-texts-that-contains-quotation-marks-by-xpath-in-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!