I have an XPath which has a single quote in XPath which is causing a SyntaxError: error.
I've tried with escape sequence:
xpath = "//label[contains(text(),'Ayuntamiento de la Vall d'Uixó - Festivales Musix')]"
But I am still facing an error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//label[contains(text(),'Ayuntamiento de la Vall d'Uixó - Festivales Musix')]' is not a valid XPath expression.
There is no quote escaping in XPath string literals. (Note: This answer applies to XPath 1.0. In higher versions of XPath, this issue is addressed - see the comment below.)
The only way to get the desired result in pure XPath is by concatenating alternately-quoted strings.
//label[contains(., concat('Ayuntamiento de la Vall d', "'", 'Uixó - Festivales Musix'))]
You can build these kinds of expressions mechanically by splitting the target string at the single quote and joining the parts again with ', "'" , ' as the new separator. Python example:
search_value = "Ayuntamiento de la Vall d'Uixó - Festivales Musix" # could contain both " and '
xpath = "//label[contains(., %s)]" % xpath_string_escape(search_value)
def xpath_string_escape(input_str):
""" creates a concatenation of alternately-quoted strings that is always a valid XPath expression """
parts = input_str.split("'")
return "concat('" + "', \"'\" , '".join(parts) + "', '')"
Some XPath libraries support bound parameters (much like SQL) to get around this, but the above is the only approach that works everywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With