python - 选择 sibling ,但中间没有任何东西

标签 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>

xpath 是否允许选择 sibling 但停在某个点?我想选择两个 <p>第一个下<h1>但不是第二个下的<h1> .修改 HTML 是不可能的,因为我正在做一些网络抓取,我正在寻找一种快速而肮脏的方法来从某个标题下的段落中提取数据:

paragraphs = target.select("~ p")

最佳答案

试试这个:

#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>

关于python - 选择 sibling ,但中间没有任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829055/

相关文章:

css - 可以显示: flex; be broken?

Java XPath "if"语句

css - 当 id 包含使用 Nokogiri 的特殊字符时,如何抓取 URL/文本

python - Pandas 洗牌列值不起作用

python - Python 类是否可以拥有可访问的成员,但不能来自该类的实例?

html - 使用 float 将元素放置在CSS的右侧

php - 菜单和搜索区域内联问题

python - 在 Python 中创建用户配置文件

python - scikit-learn 和 scipy 库之间的决定系数不同。为什么?

python - 如何从 selenium webelement 或 lxml 获取 XPath?