I have the following code line used in selenium python script:
from selenium import webdriver
driver.find_element_by_xpath(u"//span[text()='" + cat2 + "']").click()
cat2 is variable from a database list that i get like this:
db = Database()
sql = "SELECT * FROM missing
listeproduit = db.select(sql)
for record in listeproduit:
cat2 = record[6]
The probleme is when the variable contain a text like this:
cat2 = Debimetre d'air
Then the script don't works because it's an illegal xpath expression.
From my search, i understand that it's a problem with escaping the single quote in my variable cat2
From this answers :Escape single quote in XPath with Nokogiri?
They suggest to use concat() xpath function, but how to use it in my case ? Thanks for your help.
Cheers
You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.
XPath's string literals can't contain both types of quotes; you need to construct the string using the XPath concat function. For example, if you wanted to match the string "That's mine", he said. , you would need to do something like: text()=concat('"That', "'", 's mine", he said.
There is no way to escape characters at the XPath level, so you can't have a literal XPath string containing both kinds of quote.
In XPath 1.0, which is used by browsers and therefore by Selenium, there is no native way of escaping string literals (which was remedied in XPath 2.0). A few workarounds are mentioned by this poster, which includes:
concat('"', "Here's Johnny", '"', ", said Johnny.")
, which combines to the literal: "Here's Johnny", said Johnny.
.In your case, this would work:
driver.find_element_by_xpath(u"//span[text()=\"" + cat2 + "\"]").click()
Another way around this is to set an XPath variable to contain the value of your string literal, which helps in readability. But I couldn't find how to do it with the web drivers for Selenium, which typically means there is no such method available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With