python - 使用 Python 转义 XPath 文字

标签 python xml selenium

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

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\)')]

从逻辑上讲,这个问题可以通过将 ) 替换为 \) 来解决,但是仍然有其他字符需要转义。那么有没有图书馆可以以正确的方式做到这一点?

最佳答案

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

关于python - 使用 Python 转义 XPath 文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6937525/

相关文章:

java - 在junit4中执行测试方法

xml - JAX RS - JSON 和 XML 循环/循环引用错误

Javascript 代码不会打开 XML 文件并放入表中

python - 从字母组合生成字符串的最佳选择是 python 还是 bash?

python - 将 Python datetime.datetime 对象插入 MySQL

java - org.apache.axiom.om.impl.llom.OMTextImpl 无法转换为 org.apache.axiom.om.OMElement

javascript - Protractor 和 Grunt 之间的区别?

selenium - getAttribute 未返回 selenium 中样式的完整值

python - 如何创建与网格坐标一起使用的字母列表? (即 a、b、...、z、aa、bb、...、zz、aaa 等)

python - 如何在Python3.6和CentOs上安装Twisted + Scrapy