我的 XPath 查询遇到问题。我必须解析一个 div,它被划分为未知数量的“部分”。其中每一个都由 h5 和部分名称分隔。可能的部分标题列表是已知的,并且每个标题只能出现一次。此外,每个部分可以包含一些 br 标签。所以,假设我想提取“SecondHeader”下的文本。
HTML
<div class="some-class">
<h5>FirstHeader</h5>
text1
<h5>SecondHeader</h5>
text2a<br>
text2b
<h5>ThirdHeader</h5>
text3a<br>
text3b<br>
text3c<br>
<h5>FourthHeader</h5>
text4
</div>
预期结果(第二部分)
['text2a', 'text2b']
Query #1
//text()[following-sibling::h5/text()='ThirdHeader']
结果#1
['text1', 'text2a', 'text2b']
这显然有点太多了,所以我决定将结果限制为所选标题和之前标题之间的内容。
Query #2
//text()[following-sibling::h5/text()='ThirdHeader' and preceding-sibling::h5/text()='SecondHeader']
结果#2
['text2a', 'text2b']
取得的成果符合预期。但是,这不能使用 - 我不知道 SecondHeader/ThirdHeader 是否会存在于解析的页面中。在查询中只需要使用一个章节标题。
Query #3
//text()[following-sibling::h5/text()='ThirdHeader' and not[preceding-sibling::h5/text()='ThirdHeader']]
结果#3
[]
你能告诉我我做错了什么吗?我已经在谷歌浏览器中测试过了。
If all h5
元素和文本节点是兄弟节点,您需要按部分分组,一个可能的选项是简单地按计数选择文本节点h5
之前的。
使用示例lxml
(Python)
>>> import lxml.html
>>> s = '''
... <div class="some-class">
... <h5>FirstHeader</h5>
... text1
... <h5>SecondHeader</h5>
... text2a<br>
... text2b
... <h5>ThirdHeader</h5>
... text3a<br>
... text3b<br>
... text3c<br>
... <h5>FourthHeader</h5>
... text4
... </div>'''
>>> doc = lxml.html.fromstring(s)
>>> doc.xpath("//text()[count(preceding-sibling::h5)=$count]", count=1)
['\n text1\n ']
>>> doc.xpath("//text()[count(preceding-sibling::h5)=$count]", count=2)
['\n text2a', '\n text2b\n ']
>>> doc.xpath("//text()[count(preceding-sibling::h5)=$count]", count=3)
['\n text3a', '\n text3b', '\n text3c', '\n ']
>>> doc.xpath("//text()[count(preceding-sibling::h5)=$count]", count=4)
['\n text4\n']
>>>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)