1

I have a line where I check if a certain element by partial text exists on the page.

self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text)

So it is possible that item_text has a single quote in the string. For example "Hanes Men's Graphic ".

It the becomes self.b.find_element_by_xpath(".//*[contains(text(), 'Hanes Men's Graphic ')]")

In that case i get the error:

InvalidSelectorError: Unable to locate an element with the xpath expression .//*[contains(text(), 'Hanes Men's Graphic ')] because of the following error:
SyntaxError: The expression is not a legal expression.

What operation should I perform on item_text before it is used in self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text)

I know that I can use single quotes around the expression and use double quotes inside, but that's not the solution I'm looking for.

raitisd
  • 3,875
  • 5
  • 26
  • 37
  • [You can check on how to escape quotes in python](http://stackoverflow.com/a/3708167/3122133) – Madhan Jul 12 '16 at 10:28
  • 1
    Possible duplicate of [How to Escape Single Quotes in Python on Server to be used in Javascript on Client](http://stackoverflow.com/questions/3708152/how-to-escape-single-quotes-in-python-on-server-to-be-used-in-javascript-on-clie) – Madhan Jul 12 '16 at 10:29

2 Answers2

4

try as below :-

self.b.find_element_by_xpath(".//*[contains(text(), \"Hanes Men's Graphic\")]")

or

self.b.find_element_by_xpath('.//*[contains(text(), "%s")]' % item_text)

or

self.b.find_element_by_xpath(".//*[contains(text(), \"%s\")]" % item_text)

Hope it will work..:)

Saurabh Gaur
  • 23,507
  • 10
  • 54
  • 73
1

It might be that the xpath implementation won't allow double quotes for the string so you'll need to do something like

if (item_text.find("'")):
    item_text= item_text.replace("'", "', \"'\", '")
    item_text= "concat('" + item_text+ "')"
else:
    item_text = "'" + item_text + "'"

self.b.find_element_by_xpath(".//*[contains(text(), %s)]" % item_text)
the-noob
  • 1,322
  • 2
  • 14
  • 19