查找元素在Beautiful Soup中有多少级别的子元素

时间:2011-02-04 04:38:37

标签: python beautifulsoup html-parsing

我在试图找出一个元素有多少“级别”的子元素时遇到了问题。例如

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

在此代码中,id为first的div将具有4个级别的子元素。

基本上我需要弄清楚元素是否有2个或更少的子级别。

1 个答案:

答案 0 :(得分:0)

以下是使用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)