2

I hope this is a small problem:

I want to search for a text, that can contain doublequotes " and/or singelquotes '. Now I can use this:

"//a[contains(text(), '"+ mytext +"')]" 

or this:

'//a[contains(text(), "'+ mytext +'")]'

but if i have mytext is something like this:

a'b"c 

i get (of course) a xpath-error (Invalid XPath-Expression). How can I avoid it?

dynobo
  • 675
  • 1
  • 6
  • 15

2 Answers2

2

In XPath 2.0 the delimiting quotes of a string literal can be included in the literal by doubling: "He said, ""I can't""".

In XPath 1.0, such a string can't be written as a literal, but it can be expressed using concat(): concat("He said, ", '"', "I can't", '"')

Of course, if such an XPath expression is then to be written as a string literal in a host language such as Python, the quotes must be further escaped according to Python rules.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • For use in Selenium (an XPath 1.0 application), I actually wrote an escape-quotes-splitting-into-concat()-arguments routine. It was easier to write than it is to describe :-) – Ross Patterson Aug 24 '13 at 22:26
-1

Use Python triple quotes r"""a'b"c""". Inside the xpath, use an escape .

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • I tried this: `mytext = mytext.replace('"', '"""')` `link = sess.at_xpath('//a[contains(text(), "'+ mytext +'")]')` but I still get the xpath-error. And how do I escape inside the xpath? – dynobo Aug 24 '13 at 18:55