【发布时间】:2020-06-05 21:06:53
【问题描述】:
我正在尝试在 XHTML ElementTree 中查找所有标题元素,我想知道是否有任何方法可以使用 XPath 做到这一点。
<body>
<h1>title</h1>
<h2>heading 1</h2>
<p>text</p>
<h3>heading 2</h3>
<p>text</p>
<h2>heading 3</h2>
<p>text</p>
</body>
我的目标是让所有标题元素按顺序排列,天真的解决方案行不通:
for element in tree.iterfind("h*"):
foo(element)
因为它们应该是有序的,所以我不能单独遍历每个标题元素
headings = {f"h{n}" for n in range(1, 6+1)}
for heading in headings:
for element in tree.iterfind(heading):
foo(element)
(但 for element in filter(lambda el: el.tag in headings, tree.iterfind()) 有效)
我不能使用正则表达式,因为它在 cmets 上中断(不使用字符串标签)
import re
pattern = re.compile("^h[1-6]$")
is_heading = lambda el: pattern.match(el.tag)
for element in filter(is_heading, tree.iterfind()):
foo(element)
(但 is_heading = lambda el: isinstance(el.tag, str) and pattern.match(el.tag) 有效)
没有一个解决方案特别优雅,所以我想知道是否有更好的方法可以使用 xpath 按顺序查找所有标题元素?
【问题讨论】:
-
XPath 支持在 ElementTree 中受到限制;你能用lxml吗?
-
以下任何答案是否有帮助或您仍有问题?
标签: python-3.x xml xpath elementtree