如何在ElementTree元素中表示多个文本部分?

2024-09-30 18:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用ElementTree来处理一些html。我认为html是一种xml语言,所以应该可以。你知道吗

在html中,文本中可以有标记:

<p>
This paragraph <em>has some</em> emphasised words.
</p>

所以“p”元素有一些文本(“这个段落”),一个子元素(“em”)和更多的文本(“强调词”)

但是ElementTree元素有一个文本属性,它是一个字符串。子元素在一个列表中,但是文本都在一个字符串中。你知道吗

如何在ElementTree中表示这个html?有可能吗?你知道吗


Tags: 字符串标记文本语言元素htmlsomexml
1条回答
网友
1楼 · 发布于 2024-09-30 18:28:04

你想解析它吗?你知道吗

import xml.etree.ElementTree as ET

def processElem(elem):
    if elem.text is not None:
        print elem.text
    for child in elem:
        processElem(child)
        if child.tail is not None:
            print child.tail

xml = '''<p>
This paragraph <em>has some</em> emphasised words.
</p>'''

root = ET.fromstring(xml)
processElem(root)

提供:

This paragraph 
has some
 emphasised words.

或者你想修改HTML?你知道吗

from xml.etree.ElementTree import Element, SubElement, tostring
top = Element('p')
top.text = 'This paragraph '
child_with_tail = SubElement(top, 'em')
child_with_tail.text = 'has some'
child_with_tail.tail = ' emphasised words.'
print tostring(top)

提供:

<p>This paragraph <em>has some</em> emphasised words.</p>

相关问题 更多 >