How to properly escape single and double quotes

后端 未结 3 1700
再見小時候
再見小時候 2021-01-13 00:01

I have a lxml etree HTMLParser object that I\'m trying to build xpaths with to assert xpaths, attributes of the xpath and text of that tag. I ran into a problem when the te

3条回答
  •  萌比男神i
    2021-01-13 00:25

    The solution is applicable If u r using python lxml. Its better to leave the escaping for lxml. We can do this by using lxmlvariables. Suppose We have xpath as below:

    //tagname[text='some_text']`
    

    If some_text has both single and double quotes, then it causes "Invalid Predicate error". Neither escaping work for me nor triple quotes. Because xml won't accept triple quotes.

    Solution worked for me is lxml variables.

    We convert the xpath as below:

    //tagname[text = $var]
    

    Then execute

    find = etree.XPath(xpath)
    

    Then evaluate these variable to its value

    elements = find(root, {'var': text})
    

提交回复
热议问题