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

后端 未结 2 1792
死守一世寂寞
死守一世寂寞 2020-12-11 04:38

I have the following code line used in selenium python script:

from selenium import webdriver

driver.find_element_by_xpath(u\"//span[text()=\'\" + cat2 + \"         


        
2条回答
  •  暖寄归人
    2020-12-11 05:18

    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.

提交回复
热议问题