我有以下html:
<div id = "big">
<span>header 1</span>
<ul id = "outer">
<li id = "inner">aaa</li>
<li id = "inner">bbb</li>
</ul>
<span>header 2</span>
<ul id = "outer">
<li id = "inner">ccc</li>
<li id = "inner">ddd</li>
</ul>
</div>
我希望它按顺序循环它:
header 1
aaa
bbb
header 2
ccc
ddd
我尝试遍历每个 ul ,然后打印标题和 li 值。但是,我不知道如何获取与 ul 关联的 span 标头。
sets = tree.xpath("//div[@id='big']//ul[@id='outer']")
for set in sets:
# Print header. Not sure how to get it
header = set.xpath(".//li/preceding-sibling::span")
print header
# Print texts. This works.
values = set.xpath(".//li//text()")
for v in values:
print v
仅循环所有文本节点是行不通的,因为我需要知道它是标题还是 li 值。