xpath - 在 Scrapy 中选择下一个 sibling 的序列

标签 xpath scrapy

我要废弃以下 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/

相关文章:

java - 如何在 Java 中使用 Selenium WebDriver 单击列表中的链接

java - 不明白为什么我会收到这个 - 'Error: Value storage corrupted: negative offset'

python - 如何使用 Scrapy 抓取亚马逊搜索的所有结果?

未调用python连接信号

python - 如何访问 Scrapy CrawlSpider 中的特定 start_url?

selenium - 使用 Selenium 绕过 Youtube 登录 + reCaptcha

xml - 如果元素存在且非空,如何使用 XPath 判断?

python - Lxml html xpath 上下文

c# - 在 XPather.com 上使用 XML 命名空间的奇怪 XPath 行为?

scrapy - Scrapy 暂停/恢复如何工作?