我正在编写一个通用库,用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)
Run Code Online (Sandbox Code Playgroud)
我想在将消息传递给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)')]
Run Code Online (Sandbox Code Playgroud)
虽然下面的查询将返回所需的组件:
//span[@class='error'][contains(.,'The number of memory slots used \(32\) exceeds the number of memory slots that are available \(16\)')]
Run Code Online (Sandbox Code Playgroud)
按理这个问题可以通过更换得到解决)与\)此特定字符串文字,但后来还是有其他字符需要进行转义.那么有没有任何图书馆以适当的方式做到这一点?
括号在那里应该没问题.它们位于由撇号分隔的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)
Run Code Online (Sandbox Code Playgroud)