Reputation: 4425
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.
Upvotes: 1
Views: 11041
Reputation: 1342
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)
Upvotes: 2
Reputation: 23805
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..:)
Upvotes: 4