我正在使用 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/