简体   繁体   中英

Find how many levels of child elements an element has in Beautiful Soup

I'm having a problem trying to find out how many "levels" of child elements an element has. For example

<div id="first">
 <div id="second">
  <div id="third">
   <div id="fourth">
    <div id="fifth">
    </div>
   </div>
  </div>
 </div>
 <div id="second2">
 </div>
</div>

In this code the div with the id of first would have 4 levels of child elements.

Basically I need to figure out whether the element has 2 or less child levels.

Here's an example using xml.etree.ElementTree ;

import xml.etree.ElementTree as et

def height(branch):
    if len(branch) == 0:
        return 0
    else:
        return max([height(child) for child in branch.getchildren()])+1

tree = et.fromstring(text)
print height(tree)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM