小编典典

如何在XPath中处理单引号

selenium

我在一行中检查页面上是否存在按部分文本表示的某个元素。

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

因此,可能item_text在字符串中包含单引号。例如"Hanes Men's Graphic "

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

在那种情况下,我得到错误:

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.

item_text在将其用于之前,我应该执行什么操作self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text)

我知道我可以在表达式周围使用单引号,并在内部使用双引号,但这不是我要寻找的解决方案。


阅读 860

收藏
2020-06-26

共1个答案

小编典典

尝试如下:-

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

要么

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

要么

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

希望它能工作.. :)

2020-06-26