2010-04-27 30 views

Trả lời

56

Bạn có thể sử dụng XPath để tìm kiếm đệ quy:

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

iterfind() lặp trên tất cả các yếu tố phù hợp với biểu thức đường dẫn

findall() trả về một danh sách phù hợp với yếu tố

find() trả một cách hiệu quả chỉ là người đầu tiên phù hợp với

findtext() ret Đỉnh nội dung .text của trận đấu đầu tiên

Ví dụ minh họa:

>>> 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]")) 
[] 

tham khảo: http://lxml.de/tutorial.html#elementpath

(Câu trả lời này là có liên quan chọn lọc lựa chọn từ nội dung tại liên kết này)

Các vấn đề liên quan