我有一个复杂的 HTML 文档,其中嵌套了 <div>
标签,例如以下内容:
<html>
<body>
<div id="one">
<p>1. Get this div!</p>
</div>
<div id="two">
<div>
<div id="three">
<p>2. Get this div!</p>
</div>
</div>
<div id="four">
<p>3. Get this div!</p>
</div>
</div>
</body>
</html>
我正在尝试使用以下代码:
soup = BeautifulSoup(html, 'html.parser')
div_list = soup.find_all('div')
但是,上面的代码仅获取最顶层的 div,这意味着它将仅返回 id 为“one”和“two”的 div。 但是,我想使用 BeautifulSoup 返回 id 为“一”、“三”和“四”的 div 列表。我怎样才能做到这一点?
最佳答案
可以直接检查找到的分区中是否还有更多的分区:
[d for d in soup.findAll('div') if not d.find('div')]
#[<div id="one"><p>1. Get this div!</p></div>,
# <div id="three"><p>2. Get this div!</p></div>,
# <div id="four"><p>3. Get this div!</p></div>]
关于Python 美丽汤 : How to find all lowest-level divs (divs which don't contain nested divs)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52049233/