Christina
Christina

Reputation: 43

JavascriptExecutor XPath with apostrophe

I'm trying to find a text element using XPath using JavascriptExecutor. The problem is that the text has an apostrophe, and I don't know how to escape it in this case. Normally it is just enough with \". Could you help me?

I have already tried the following options:

((JavascriptExecutor)driver).executeScript("var path = '//*[text()=\"d'arrivée\"]/following-sibling::div/div';
var x = document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;x.style.display='block';");`

and

((JavascriptExecutor)driver).executeScript("var path = '//*[text()=\"d\"arrivée\"]/following-sibling::div/div';
var x = document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;x.style.display='block';");`

Upvotes: 1

Views: 964

Answers (3)

Andersson
Andersson

Reputation: 52665

Try below expression with escaped apostrophe:

'//*[text()="d\'arrivee"]/following-sibling::div/div'

When using a string between single quotes, you should escape an apostrophe with a single backslash. Double quotes don't need to be escaped in this type of string.

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163322

First construct the XPath expression you need. In XPath 1.0 the only way to write a literal apostrophe is to use double-quotes as the string delimiter, so the XPath expression is:

//*[text()="d'arrivee"]/following-sibling::div/div

(although using "." rather than "text()" is better practice).

Then think about how to escape this as a string literal in your chosen host language, which in this case is Javascript. In Javascript, you can use either ' or " as the string delimiter, and you must then escape any occurrences of the string delimiter with a backslash. So it becomes either

"//*[text()=\"d'arrivee\"]/following-sibling::div/div"

or

'//*[text()="d\'arrivee"]/following-sibling::div/div'

Upvotes: 1

PrinceOFF
PrinceOFF

Reputation: 95

As a variant try to find another Xpath-locator without apostrophe. Do not use function "text()" or use part of text through with "contains()". I think it is real.

Upvotes: 0

Related Questions