简体   繁体   中英

How to deal with single quote in xpath

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.

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..:)

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM