Python 美丽汤 : How to find all lowest-level divs (divs which don't contain nested divs)?

标签 python html beautifulsoup

我有一个复杂的 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/

相关文章:

python - 导入错误 : No module named gtk

python - 仅使用标准库的 Python 中的基本 cometd

html - 边距自动不是由宽度决定的

python - 如何解析 div 并获取不同行中的每个 <strong> 标签内容?

python - 通过 3D 表面绘制 2D 平面

javascript - 在 IE 中显示法语字符的问题

javascript - 根据 hidden 有值的输入类型统计 <li>

python - 如何在 Python/BS4 中向我的网页抓取脚本添加代理和 header ?

Python,将所有链接、标题和正文文本附加到一个数组或 json 文件中

python - token 名称 'app' 未定义。 flask