lxml - 获取一个扁平的元素列表

时间:2014-10-06 19:45:41

标签: python dom tree lxml flatten

我想压扁lxml etree(特别是HTML,如果重要的话。)我如何获得树中所有元素的平面列表?

1 个答案:

答案 0 :(得分:8)

您可以使用.iter()方法,如下所示:

from lxml import etree

xml = etree.XML('''<html><body>
                   <p>hi there</p><p>2nd paragraph</p>
                   </body></html>''')

# If you want to visit all of the descendants
for element in xml.iter():
    print element.tag

# Or, if you want to have a list of all the descendents
all_elements = list(xml.iter())
print [element.tag for element in all_elements]