使用Python转义XPath文字

时间:2011-08-04 07:14:21

标签: python xml selenium

我正在编写一个通用库,用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查询之前转义消息,因此它可以支持“消息”是否类似“使用的内存插槽数(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\)')]

逻辑上,此问题可以通过将)替换为\)来解决此特定字符串文字,但是仍然需要转义其他字符。那么有没有任何图书馆以适当的方式做到这一点?

1 个答案:

答案 0 :(得分:7)

圆括号应该没问题。它们位于由撇号分隔的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)