Python 如何处理xpath中的单引号
我有一行,通过部分文本检查页面上是否存在某个元素Python 如何处理xpath中的单引号,python,selenium,xpath,Python,Selenium,Xpath,我有一行,通过部分文本检查页面上是否存在某个元素 self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text) 因此,item\u text可能在字符串中有一个引号。例如“Hanes男式图案” 它变成了self.b.find_元素\u by_xpath(“./*[contains(text(),'Hanes Men's Graphic')]”) 在这种情况下,我会得到错误: InvalidSelectorErr
self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text)
因此,item\u text
可能在字符串中有一个引号。例如“Hanes男式图案”
它变成了self.b.find_元素\u 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.
在self.b.find_元素\u by_xpath(“./*[contains(text(),'%s')]”%item_text)中使用item_text之前,我应该对它执行什么操作
我知道我可以在表达式周围使用单引号,在表达式内部使用双引号,但这不是我要寻找的解决方案。请尝试以下操作:-
self.b.find_element_by_xpath(".//*[contains(text(), \"Hanes Men's Graphic\")]")
或
或
希望它能起作用。:)尝试以下操作:-
self.b.find_element_by_xpath(".//*[contains(text(), \"Hanes Men's Graphic\")]")
或
或
希望它能工作。:)可能是xpath实现不允许字符串使用双引号,因此您需要执行以下操作
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)
可能xpath实现不允许字符串使用双引号,因此需要执行以下操作
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)
很好,谢谢。将等待更多的答案,如果没有更好的进来,我会批准这个:)很好,谢谢。我将等待更多的答案,如果没有更好的答案,我将批准这一条:)可能的重复