Venkat Kishore
Venkat Kishore

Reputation: 67

How to deal with single and double quotes in xpath in Python

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.

Upvotes: 4

Views: 6434

Answers (4)

Tomalak
Tomalak

Reputation: 338128

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.

Upvotes: 4

undetected Selenium
undetected Selenium

Reputation: 193058

To construct an within double quotes which includes text with single quotes in Python you can use the following Locator Strategy:

xpath = "//label[text()=\"Ayuntamiento de la Vall d'Uixó  - Festivales Musix\"]"

Upvotes: 0

m_____z
m_____z

Reputation: 1591

You could define the search string using triple quotes - then you won't have to worry about any potential special characters and quotes inside your string.

Here is an example:

xpath = """//label[contains(text(), "Ayuntamiento de la Vall d'Uixó  - Festivales Musix")]"""

If you also want to include backslashes in your string, you can use raw triple quotes:

xpath = r"""raw triple quotes string allow the use of '\'"""

See PEP257 for more details.

Upvotes: -1

KunduK
KunduK

Reputation: 33384

Try the below xpath.

xpath = "//label[contains(text(), \"Ayuntamiento de la Vall d'Uixó  - Festivales Musix\")]"

Upvotes: -1

Related Questions