2011-02-04 7 views
0

요소에있는 하위 요소의 "레벨"수를 파악하는 데 문제가 있습니다. 예를 들어,요소에 포함 된 하위 요소의 수를 확인하십시오. Beautiful Soup

<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를 가진 div는 4 레벨의 하위 요소를 갖습니다.

기본적으로 요소의 하위 수준이 2 개 이하인지 알아야합니다.

+0

그냥 알아 내거나 내용을 확인 하시겠습니까? – KyleWpppd

+0

@KyleWpppd가 알아 내면, 실제 태그 요소를 가지고 있지는 않지만 오히려 필요하지는 않습니다. – Joshkunz

답변

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) 
+0

BeautifulSoup를 사용해 보았습니다. 그러나 어떤 이유로 트리 탐색 함수 (즉, findChildren())가 예상대로 작동하지 않습니다 ... – Kimvais

관련 문제