Q:

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

I have a complex HTML document that has nested <div> tags, such as the following:
<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>

And I am attempting to use the following code:
soup = BeautifulSoup(html, 'html.parser')
div_list = soup.find_all('div')

However, the code above only gets the topmost level divs, which means it will return only divs with ids "one" and "two". However, I would like to use BeautifulSoup to return a list of divs with ids "one", "three", and "four". How can I accomplish this?

A:

You can directly check whether any of the found divisions has more divisions inside:
[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>]

