58
<?xml version="1.0" ?>
<data>
    <test >
        <f1 />
    </test >
    <test2 >
        <test3>
         <f1 />
        </test3>
    </test2>
    <f1 />
</data>

lxml を使用すると、タグ「 f1 」を再帰的に見つけることができますか? findall メソッドを試しましたが、直系の子に対してのみ機能します。

私はこれのためにBeautifulSoupに行くべきだと思います!!!

4

2 に答える 2

90

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>]
于 2010-04-27T18:38:18.057 に答える
42

iterfind()パス式に一致するすべての要素を反復処理します

findall()一致する要素のリストを返します

find()最初の一致のみを効率的に返す

findtext()最初の一致の .text コンテンツを返します

実例:

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

(この回答は、このリンクのコンテンツからの関連する選択です)

于 2012-01-24T17:49:54.337 に答える