我有一个这样的文档:
<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>
我想提取 p[class=top] 和 p[class=end] 段落之间的所有内容。
有什么好的方法可以用 BeautifulSoup 做到这一点吗?
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 标记的属性而不是字符串节点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)