如何使用LXML递归查找XML标签?

67 投票
2 回答
86929 浏览
提问于 2025-04-15 22:05
<?xml version="1.0" ?>
<data>
    <test >
        <f1 />
    </test >
    <test2 >
        <test3>
         <f1 />
        </test3>
    </test2>
    <f1 />
</data>

使用lxml库,能不能递归地查找标签“f1”?我试过findall这个方法,但它只对直接子元素有效。

我觉得我应该使用BeautifulSoup来解决这个问题!!!

2 个回答

48

iterfind() 是一个可以遍历所有符合路径表达式的元素的函数。

findall() 会返回一个包含所有匹配元素的列表。

find() 则是高效地返回第一个匹配的元素。

findtext() 会返回第一个匹配元素的文本内容。

举例说明:

>>> root = etree.XML("<root><a x='123'>aText<b/><c/><b/></a></root>")
#Find a child of an Element:
>>> print(root.find("b"))
None
>>> print(root.find("a").tag)
a
#Find an Element anywhere in the tree:
>>> print(root.find(".//b").tag)
b
>>> [ b.tag for b in root.iterfind(".//b") ]
['b', 'b']
#Find Elements with a certain attribute:
>>> print(root.findall(".//a[@x]")[0].tag)
a
>>> print(root.findall(".//a[@y]"))
[]

参考链接: http://lxml.de/tutorial.html#elementpath

(这个回答是从该链接内容中挑选出来的相关部分)

103

你可以使用XPath来进行递归搜索:

>>> from lxml import etree
>>> q = etree.fromstring('<xml><hello>a</hello><x><hello>b</hello></x></xml>')
>>> q.findall('hello')     # Tag name, first level only.
[<Element hello at 414a7c8>]
>>> q.findall('.//hello')  # XPath, recursive.
[<Element hello at 414a7c8>, <Element hello at 414a818>]

撰写回答