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.
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.
'
WebElement elem = findElement(By.xpath(String.format("//*[contains(.,\"%s\")]", arg)));
"
WebElement elem = findElement(By.xpath(String.format("//*[contains(.,'%s')]", arg)));
'
and "
Escape all "
in arg with arg.replace("\"", """);
and build your Xpath like
WebElement elem = findElement(By.xpath(String.format("//*[contains(.,\"%s\")]", arg)));