如何获取BeautifulSoup标签的所有直接children?

How to get all direct children of a BeautifulSoup Tag?

如何使用 BeautifulSoup (bs4) 检索(非递归)所有 children?

<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

有更简洁的方法吗?

如果您只想 select 直接后代,您可以将 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>