【问题标题】:Find how many levels of child elements an element has in Beautiful Soup在 Beautiful Soup 中查找一个元素有多少级子元素
【发布时间】:2011-02-04 04:38:37
【问题描述】:

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

<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 个或更少的子级别。

【问题讨论】:

  • 自己搞清楚,还是把内容也搞定?
  • @KyleWpppd 想一想,它不会有实际的标签元素,但它不是必需的。

标签: python beautifulsoup html-parsing


【解决方案1】:

这是一个使用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)

【讨论】:

  • 我尝试使用 BeautifulSoup,但由于某种原因,树遍历函数(即findChildren())没有按我预期的方式工作...
猜你喜欢
  • 2018-10-24
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多