Search code examples
seleniumxpathfindelement

Find texts that contains quotation marks by xpath in Selenium


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.


Solution

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