I'm writing a common library to setup an automation test suite with Selenium 2.0 Python's 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)
I would like to escape 开发者_StackOverflow中文版the message before passing it to XPath query, so it can support if 'message' is something like "The number of memory slots used (32) exceeds the number of memory slots that are available (16)"
Without escaping, the xpath query won't work since it contains '(' and ')'
Which library can we use to do this in Python?
I know that this is a simple question, but I don't have so much experience in Python (just started).
Thanks in advance.
Additional info:
During testing in firebug, the query below will return no result:
//span[@class='error'][contains(.,'The number of memory slots used (32) exceeds the number of memory slots that are available (16)')]
While the query below will return the desired component:
//span[@class='error'][contains(.,'The number of memory slots used \(32\) exceeds the number of memory slots that are available \(16\)')]
Logically this problem can be solved by replacing )
with \)
for this particular string literal, but then there are still the other characters need to be escaped. So is there any library to do this in a proper way?
Parentheses should be fine there. They're inside an XPath string literal delimited by apostrophe, so they do not prematurely end the contains
condition.
The problem is what happens when you have apostrophes in your string, since those do end the string literal, breaking the expression. Unfortunately there is no string escaping scheme for XPath string literals, so you have to work around it using expressions to generate the troublesome characters, typically in the form concat('str1', "'", 'str2')
.
Here's a Python function to do that:
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)
精彩评论