XPath variables in lxml

余生颓废 提交于 2020-02-02 15:33:09

问题


I want to use XPath variables to match a user-defined tag and avoid XPath injection vulnerabilities. I have tried

from lxml import etree
etree.fromstring('<div><p>Hello</p></div>').xpath('.//$var', var='p')

but I get

XPathEvalError: Invalid expression

What am I doing wrong?


回答1:


You cannot use a variable as the node test part of a location step in an expression. It has to be a literal name. But you can use a wildcard and a predicate. The following works:

etree.fromstring('<div><p>Hello</p></div>').xpath('.//*[loca‌​l-name() = $var]', var='p')


来源:https://stackoverflow.com/questions/42783305/xpath-variables-in-lxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!