问题描述
我有一行用于检查页面上是否存在部分文本的某个元素.
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)
因此,item_text
可能在字符串中有一个单引号.例如Hanes Men's Graphic"
.
So it is possible that item_text
has a single quote in the string. For example "Hanes Men's Graphic "
.
它变成了 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.
在 self.b.find_element_by_xpath(".///*[contains(text(), '%s')]" 中使用
item_text
之前,我应该对它执行什么操作% item_text)
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.
推荐答案
尝试如下:-
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)
希望它会起作用..:)
Hope it will work..:)
这篇关于如何处理xpath中的单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!