如何获得BeautifulSoup标签的所有直接孩子?

时间:2017-12-31 19:49:41

标签: python-3.x beautifulsoup siblings

如何使用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

有更清洁的方法吗?

1 个答案:

答案 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>