【问题标题】:Extracting text after tag in Python's ElementTree在 Python 的 ElementTree 中提取标签后的文本
【发布时间】:2012-03-29 06:08:48
【问题描述】:

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

【问题讨论】:

    标签: python text xml-parsing elementtree


    【解决方案1】:

    元素有一个tail 属性——所以你要的是element.tail,而不是element.text

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

    【讨论】:

    • 太棒了。我之前尝试过使用.tail,但我在我的 el 对象上使用了它。没有意识到我必须在 img 上使用它。谢谢你开导我!
    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 2018-06-18
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多