簡體   English   中英

在Python的ElementTree中的標記后提取文本

[英]Extracting text after tag in Python's ElementTree

這是XML的一部分:

<item><img src="cat.jpg" /> Picture of a cat</item>

提取標簽很容易。 做就是了:

et = xml.etree.ElementTree.fromstring(our_xml_string)
img = et.find('img')

但是,如何立即獲得文本( 貓的照片 )呢? 執行以下操作將返回一個空白字符串:

print et.text

元素具有tail屬性-因此,您需要的是element.text而不是element.tail

>>> import lxml.etree
>>> root = lxml.etree.fromstring('''<root><foo>bar</foo>baz</root>''')
>>> root[0]
<Element foo at 0x145a3c0>
>>> root[0].tail
'baz'

或者,例如:

>>> et = lxml.etree.fromstring('''<item><img src="cat.jpg" /> Picture of a cat</item>''')
>>> et.find('img').tail
' Picture of a cat'

這也適用於普通的ElementTree:

>>> import xml.etree.ElementTree
>>> xml.etree.ElementTree.fromstring(
...   '''<item><img src="cat.jpg" /> Picture of a cat</item>'''
... ).find('img').tail
' Picture of a cat'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM