如何在lxm中表示“当前节点中有子节点”

2024-04-24 10:42:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将html文件解析为:
1) 当td中有子模式时,请输出stage1
2) 当td中没有子模式时,请输出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")

Tags: innodedatahtmltablerootlxmltr
1条回答
网友
1楼 · 发布于 2024-04-24 10:42:20

一种方法是使用getchildren()方法:

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

印刷品:

stage1
stage2

因为第一个tdspan在里面,第二个td没有任何子级。你知道吗

升级版本:

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()

相关问题 更多 >