使用BeautifulSoup提取两个节点之间的兄弟节点
我有一个这样的文档:
<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标签的属性,而不是字符串节点。