如何使用BeautifulSoup(bs4)检索(非递归)所有孩子?
<div class='body'><span>A</span><span><span>B</span></span><span>C</span></div>
我想得到这样的块:
block1 : <span>A</span>
block2 : <span><span>B</span></span>
block3 : <span>C</span>
我这样做:
for j in soup.find_all(True)[:1]:
if isinstance(j, NavigableString):
continue
if isinstance(j, Tag):
tags.append(j.name)
# Get siblings
for k in j.find_next_siblings():
# k is sibling of first element
有更清洁的方法吗?
答案 0 :(得分:7)
如果您只想选择直接后代,可以将recursive
参数设置为False
。
您提供的html示例:
from bs4 import BeautifulSoup
html = "<div class='body'><span>A</span><span><span>B</span></span><span>C</span></div>"
soup = BeautifulSoup(html, "lxml")
for j in soup.div.find_all(recursive=False):
print(j)
<span>A</span>
<span><span>B</span></span>
<span>C</span>