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

标签 python python-2.7 elementtree

我正在使用 ElementTree 来处理一些 html。我认为html是一种xml语言,所以应该没问题。

在 html 中,您可以在文本中添加标签:

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

因此“p”元素有一些文本(“This paragraph”)、一个子元素(“em”)和一些更多文本(“强调的单词”。)

但是ElementTree元素有一个文本属性,它是一个字符串。子元素位于一个列表中,但文本全部位于一个字符串中。

如何在 ElementTree 中表示此 html?可能吗?

最佳答案

你想解析它吗?

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>

关于python - 如何在 ElementTree 元素中表示多个文本部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41079204/

相关文章:

python - 使用 Python 解析 Alexa XML

python 解析 xml 字符串

python - 将 elementtree 转储到 xml 文件中

python - 引用数组

python - 使用 python 脚本从 hdfs (hadoop) 目录获取文件列表

python - 为什么 Ruby 比 Python 更适合 Rails?

python - 建议正则表达式中的子字符串应根据长度排序的建议背后的原因是什么?

python - 验证所有请求的最佳方式?

python - 在3个文本文件之间写入正数和负数

python - 如何连接同一数据帧中的 2 列,但从第 1 列获取行 a 到 d,从第 2 列获取 m 到 p?