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

后端 未结 2 1793
死守一世寂寞
死守一世寂寞 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:21

    Here is a Python function I've just wrote that escapes a string to use in an XPath 1.0 expression, using the trick described in @Abel's answer:

    def escape_string_for_xpath(s):
        if '"' in s and "'" in s:
            return 'concat(%s)' % ", '\"',".join('"%s"' % x for x in s.split('"'))
        elif '"' in s:
            return "'%s'" % s
        return '"%s"' % s
    

    Note that it adds the appropriate kind of quotes around your string, so be sure not to add extra quotes around the return value.

    Usage example:

    escaped_title = escape_string_for_xpath('"that\'ll be the "day"')
    
    driver.find_element_by_xpath('//a[@title=' + escaped_title + ']')
    

提交回复
热议问题