我要废弃以下 html
<h2>
<span id="title">Title</span>
</h2>
<p>Content 1</p>
<p>Content 2</p>
<p>Content 3</p>
<p>Content 4</p>
<h2>Some other header</h2>
<p>Do not want this content</p>
我要选择的是一系列 4 <p>
标题后的标签,如果不是 <p>
,则忽略其他所有内容遇到标签。
到目前为止,我的 xpath 是 //h2[span[@id='title']]/following-sibling::p
,但这也包括不需要的
标签。
我也尝试了前面的兄弟方法,但没有运气//p[preceding-sibling::h2[span[@id='title']]]
.额外的<p>
标记仍然包括在内。
最佳答案
试试这个 xpath:
//p[preceding-sibling::h2[1][./span[@id = 'title']]]
这个 xpath 做了什么:
它搜索 p
具有 h2
的元素元素作为前面的兄弟,但在一个条件下 - 仅当它们的第一个前面的兄弟 h2
有一个 child 叫span
带属性 id
等于 title
为什么过滤 <p>Do not want this content</p>
? :
因为这个p
的前面h2
s 列出时按顺序显示:
<h2>Some other header</h2>
<h2>
<span id="title">Title</span>
</h2>
因此 h2[1][./span[@id = 'title']]
结果是假的,因此这p
不返回。
示例 xml 上的结果:
<root>
<h2>
<span id="title">Title</span>
</h2>
<p>Content 1</p>
<p>Content 2</p>
<p>Content 3</p>
<p>Content 4</p>
<h2>Some other header</h2>
<p>Do not want this content</p>
<p>Do not want this content too</p>
</root>
是:
'<p>Content 1</p>'
'<p>Content 2</p>'
'<p>Content 3</p>'
'<p>Content 4</p>'
关于xpath - 在 Scrapy 中选择下一个 sibling 的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43646685/