选择兄弟姐妹,但两者之间没有任何东西

时间:2018-02-16 14:38:48

标签: python css xpath beautifulsoup

这是一个棘手的场景:



#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>
&#13;
&#13;
&#13;

xpath是否允许选择兄弟姐妹但是在某一点停止?我想选择第一个<p>下的两个<h1>,而不是第二个<h1>下的paragraphs = target.select("~ p") 。修改HTML是不可能的,因为我正在做一些网络抓取,我正在寻找一种快速而肮脏的方式从某个标题下的段落中提取数据:

<stdio.h>

2 个答案:

答案 0 :(得分:4)

试试这个:

&#13;
&#13;
#target ~ p:not(:nth-last-of-type(-n+2)) {
  background: green;
  color: white;
}
&#13;
<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>
&#13;
&#13;
&#13;

或者

&#13;
&#13;
#target + span + p,
#target + span + p + p {
  background: green;
  color: white;
}
&#13;
<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>
&#13;
&#13;
&#13;

或者

&#13;
&#13;
#target ~ p:nth-of-type(1),
#target ~ p:nth-of-type(2) {
  background: green;
  color: white;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

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

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

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