使用BeautifulSoup提取两个节点之间的兄弟节点

7 投票
1 回答
2354 浏览
提问于 2025-04-15 20:47

我有一个这样的文档:

<p class="top">I don't want this</p>

<p>I want this</p>
<table>
   <!-- ... -->
</table>

<img ... />

<p> and all that stuff too</p>

<p class="end>But not this and nothing after it</p>

我想提取在

这两个段落之间的所有内容。

有没有什么简单的方法可以用BeautifulSoup来做到这一点呢?

1 个回答

8

node.nextSibling 属性就是你的解决办法:

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(html)

nextNode = soup.find('p', {'class': 'top'})
while True:
    # process
    nextNode = nextNode.nextSibling
    if getattr(nextNode, 'name', None)  == 'p' and nextNode.get('class', None) == 'end':
        break

这个复杂的条件是为了确保你访问的是HTML标签的属性,而不是字符串节点。

撰写回答