Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python转义XPath文本_Python_Xml_Selenium - Fatal编程技术网

用Python转义XPath文本

用Python转义XPath文本,python,xml,selenium,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 err

我正在编写一个公共库,用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\)')]

从逻辑上讲,这个问题可以通过将
替换为
\)
来解决,但是仍然有其他字符需要转义。那么有没有合适的库来实现这一点呢?

括号应该可以。它们位于由撇号分隔的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)

你确定那些父母需要逃跑吗?您可以发布一些使用示例和实际错误消息吗。