2016-07-12 57 views
0

我有一行我检查页面上是否存在部分文本的某个元素。如何处理xpath中的单引号

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. 

什么操作它是在self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text)

使用之前,我知道我可以使用item_text我应该执行表达式的单引号和内部使用双引号,但这不是我正在寻找的解决方案。

+0

[您可以检查如何逃避蟒蛇行情](http://stackoverflow.com/a/3708167/3122133) – Madhan

+1

的可能的复制[如何逃生单引号在服务器上的Python在客户端的Javascript中使用](http://stackoverflow.com/questions/3708152/how-to-escape-single-quotes-in-python-on-server-to-be-used -in-javascript-on-clie) – Madhan

回答

4

尝试如下: -

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) 

希望它会工作.. :)

+0

工程很好,谢谢。将等待更多的答案,如果没有更好的进来,我会批准这一个:) – raitisd

0

这可能是与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)