Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape single quote in xpath 1.0 in selenium for python

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

like image 564
Andronaute Avatar asked Sep 24 '15 10:09

Andronaute


People also ask

How do you escape a single quote in Python?

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.

How XPath handle single quotes?

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.

How do you escape characters in XPath?

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.


1 Answers

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:

  • First off, make sure you understand the difference between escaping in Python, which is possible, and escaping within the XPath expression
  • Then, if you simply need a single quote, surround it by double quotes, and vice versa
  • Then, if one string literal contains both double and single quotes, use something like 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.

like image 62
Abel Avatar answered Oct 22 '22 14:10

Abel