2014-04-02 4 views
1

lxml이 현재 node`에서 자식 노드가`표현할 방법 : 더가있는 경우) TD의 아이 모드가있는 경우)
1하시기 바랍니다 출력 스테이지 1
2, td의 자식 모드는 stage2를 출력하십시오내가 같은 HTML 파일 구문 분석 할

내 코드를 완료하는 방법?

for cell in set: 
    print "stage1" if cell.getchildren() else "stage2" 

인쇄 :

data=''' 
<table> 
<tr> 
<td> 
<span> hallo 
</span> 
</td> 
</tr> 
<tr> 
<td> hallo 
</td> 
</tr> 
</table> ''' 
import lxml.html 
root=lxml.html.document_fromstring(data) 
set=root.xpath('//table//tr//td') 
for cell in set: 
    if(there is a child node in current node): 
     print("stage1") 
    else: 
     print("stage2") 

답변

1

하나의 옵션이 getchildren() 방법을 사용하는 첫 번째 td 때문에

stage1 
stage2 

을 내부 span을 가지고, 두 번째 td는 아이를 가질 수 없습니다.

UPD : 난 아이 노드의 이름을 얻을 수 있습니다 2.how

for cell in set: 
    children = cell.getchildren() 
    if not children: 
     print "stage2" 
    else: 
     print "stage1" 
     for child in children: 
      print child.xpath('node()')[0].strip() 
+0

1.how XPath는'아이 :: 노드()'할를 사용하는? –

+0

@ it_is_a_literature 'UPD' 섹션을 참조하십시오. 이게 니가 찾고 있던거야? – alecxe