简体   繁体   English

如何在XPath中处理单引号

[英]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. 因此, item_text可能在字符串中包含单引号。 For example "Hanes Men's Graphic " . 例如"Hanes Men's Graphic "

It the becomes self.b.find_element_by_xpath(".//*[contains(text(), '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.

What operation should I perform on item_text before it is used in self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text) 在用于self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text)之前,我应该对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 可能是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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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