【问题标题】:Select siblings but without something in between选择兄弟姐妹,但中间没有任何东西
【发布时间】:2018-07-27 11:56:28
【问题描述】:

这是一个棘手的场景:

#target ~ p {
  background: green;
  color: white;
}
<h1 id="target">Title</h1>
<span>Some description</span>
<p>Yes</p>
<p>Yes</p>

<h1>Another Title</h1>
<span>Some description</span>
<p>No</p>
<p>No</p>

xpath 是否允许选择同级但停在某个点?我想选择第一个&lt;h1&gt; 下的两个&lt;p&gt;s,而不是第二个&lt;h1&gt; 下的那些。修改 HTML 是不可能的,因为我正在做一些网页抓取,并且我正在寻找一种从某个标题下的段落中提取数据的快速而肮脏的方法:

paragraphs = target.select("~ p")

【问题讨论】:

  • 您的查询不明确“我想选择第一个&lt;h1&gt;下的两个&lt;p&gt;s,但第二个&lt;h1&gt;下的一个”。
  • @chriskirknielsen 错字。它应该说“但不是那些”。基本上,只应选择示例中说“是”的那些。
  • 你确定它不包含父 div,所以它可能更容易定位吗?

标签: python css xpath beautifulsoup


【解决方案1】:

试试这个:

#target ~ p:not(:nth-last-of-type(-n+2)) {
  background: green;
  color: white;
}
<h1 id="target">Title</h1>
<span>Some description</span>
<p>Yes</p>
<p>Yes</p>

<h1>Another Title</h1>
<span>Some description</span>
<p>No</p>
<p>No</p>

或者

#target + span + p,
#target + span + p + p {
  background: green;
  color: white;
}
<h1 id="target">Title</h1>
<span>Some description</span>
<p>Yes</p>
<p>Yes</p>

<h1>Another Title</h1>
<span>Some description</span>
<p>No</p>
<p>No</p>

或者

#target ~ p:nth-of-type(1),
#target ~ p:nth-of-type(2) {
  background: green;
  color: white;
}
<h1 id="target">Title</h1>
<span>Some description</span>
<p>Yes</p>
<p>Yes</p>

<h1>Another Title</h1>
<span>Some description</span>
<p>No</p>
<p>No</p>

【讨论】:

    【解决方案2】:

    您可以使用下面的 XPath 表达式来获取所需的段落:

    //h1/following-sibling::p[count(preceding-sibling::h1)=1]
    

    如果你知道每个h1的文字,那么你也可以试试:

    //h1[.="Title"]/following-sibling::p[following-sibling::h1[.="Another Title"]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多