用Python转义XPath字面量

7

我正在编写一个通用库,以使用Selenium 2.0 Python的webdriver设置自动化测试套件。

def verify_error_message_present(self, message):
    try:
        self.driver.find_element_by_xpath("//span[@class='error'][contains(.,'%s')]" % message)
        self.assertTrue(True, "Found an error message containing %s" % message
    except Exception, e:
        self.logger.exception(e)

我希望在将消息传递给XPath查询之前对其进行转义,以便支持“message”为“使用的内存插槽数量(32)超过可用的内存插槽数量(16)”等内容。

如果不进行转义,XPath查询将无法正常工作,因为它包含“(”和“)”。

我们可以在Python中使用哪个库来完成这项任务?

我知道这是一个简单的问题,但我在Python方面没有太多经验(刚刚开始)。

谢谢。

附加信息:

在firebug中进行测试时,以下查询将不返回任何结果:

//span[@class='error'][contains(.,'The number of memory slots used (32) exceeds the number of memory slots that are available (16)')]

虽然下面的查询将返回所需的组件:

//span[@class='error'][contains(.,'The number of memory slots used \(32\) exceeds the number of memory slots that are available \(16\)')]

从逻辑上讲,这个问题可以通过将特定的字符串文字中的)替换为\)来解决,但是仍然需要转义其他字符。因此,是否有任何库可以以正确的方式处理这个问题?


你确定那些括号需要转义吗?能否提供一些使用示例和实际的错误信息。 - muhuk
1个回答

11

在这里使用括号是没有问题的。它们位于由撇号分隔的XPath字符串文字中,因此它们不会过早结束contains条件。

问题出在如果您的字符串中有撇号,那么会发生什么情况,因为这些撇号会结束字符串文字,从而破坏表达式。不幸的是,XPath字符串文字没有任何字符串转义方案,因此您必须使用表达式来生成有问题的字符,通常采用concat('str1', "'", 'str2')形式。

这里是一个Python函数来实现这个过程:

def toXPathStringLiteral(s):
    if "'" not in s: return "'%s'" % s
    if '"' not in s: return '"%s"' % s
    return "concat('%s')" % s.replace("'", "',\"'\",'")

"//span[@class='error'][contains(.,%s)]" % toXPathStringLiteral(message)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接