lxml中的XPath变量 [英] XPath variables in lxml

查看:44
本文介绍了lxml中的XPath变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 XPath变量来匹配用户定义的标签并避免XPath注入漏洞.我尝试过

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')

但我明白了

XPathEvalError: Invalid expression

我在做什么错了?

推荐答案

您不能将变量用作节点测试部分.它必须是文字名称.但是您可以使用通配符和谓词.以下作品:

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')

这篇关于lxml中的XPath变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆