Recently, when I tried to find a character string containing'(single quote) in the environment of Selenium + Junit, which was taken care of by autopilot and autopilot test on the web page, I made a note.
If you want to search for a string that contains'(single quote) when identifying an element with Selenium etc., you have to escape'(single quote), but unfortunately the Xpath 1.0 specification There was no way to escape'(single quotes). From XPath 2.0, for example, to escape'(single quote) in a string enclosed in'(single quote), write two'(single quote) in a row and escape like''. However, it seems that XPath 2.0 cannot be used even with the latest version of Firefox and Chrome.
So what happened after all? It became as follows.
For example, when searching for an element containing the following character string by XPath,
python
<a aria-label="App May'n-chan"Love" <1>" href="#MarketListingPlace:p=tmp.03831173739257532153.1317485953465" data-column="TITLE"><img src="gwt/placeholder_icon_24.png " role="presentation"><div> <div>May'n-chan"Love" <1></div> <div></div> </div> </a>
Do the following (when searching in the console of Firefox quantam)
$x("//a[@aria-label=concat('App May', \"'\", 'n-chan\"Love\" <1>')]")
With Selenium + Junit, it looks like the following
Search by By.xpath for Selenium + Junit
python
searchString = "App May'n-chan\"Love\" <1>";
xPathStringLiteral = toXPathStringLiteral(searchString);
searchXpath = "//a[@aria-label=" + xPathStringLiteral + "]";
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(searchXpath))
toXPathStringLiteral
python
private String toXPathStringLiteral(String string) {
if ( string.indexOf("'") == -1 ) {
return "'" + string + "'";
}
if ( string.indexOf('"') == -1 ) {
return '"' + string + '"';
}
return ("concat('" + string.replace("'", "', \"'\", '") + "')");
}
It was terribly troublesome ...
Recommended Posts