The limit of Element Tree on xpath

 ̄綄美尐妖づ 提交于 2019-12-06 05:03:32

ElementTree provides limited support for XPath expressions. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the core library.

(F. Lundh, XPath Support in ElementTree.)

For an ElementTree implementation that supports XPath (1.0), check out LXML:

>>> s = """<a>
  <b name="b1"></b>
  <b name="b2"><c /></b>
  <b name="b2"></b>
  <b name="b3"></b>
</a>"""
>>> from lxml import etree
>>> t = etree.fromstring(s)
>>> t.xpath("b[@name='b2' and c]")
[<Element b at 1340788>]

From the ElementTree documentation on XPath support.:

ElementTree provides limited support for XPath expressions. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the core library.

You've just discovered a limitation in the implementation. You could use lxml instead; it provides a ElementTree-compatible interface with complete XPath 1.0 support.

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