lxml.etree 教程4:Elements contain text

元素可以包含文本:

>>> root = etree.Element("root")
>>> root.text = "TEXT"

>>> print(root.text)
TEXT

>>> etree.tostring(root)
b'<root>TEXT</root>'

 在很多XML文档(数据中心文档)中,这是可以找到文本的唯一地方。它在树结构的底部,用一个叶标签来封装。
然而,如果XML是用来标记文本,比如(X)HTML,文本也可以出现在不同的元素中。在树结构的中间:

<html><body>Hello<br/>World</body></html>

这里,<br/>标签被文本包围。元素通过tail属性来支持。它包含这个元素直接跟随的文本,在下一个直接相连的元素之前。

>>> html = etree.Element("html")
>>> body = etree.SubElement(html, "body")
>>> body.text = "TEXT"

>>> etree.tostring(html)
b'<html><body>TEXT</body></html>'

>>> br = etree.SubElement(body, "br")
>>> etree.tostring(html)
b'<html><body>TEXT<br/></body></html>'

>>> br.tail = "TAIL"
>>> etree.tostring(html)
b'<html><body>TEXT<br/>TAIL</body></html>'

 .text和.tail属性足够用来代表一个XML文档中的任意文本。

>>> etree.tostring(br)
b'<br/>TAIL'
>>> etree.tostring(br, with_tail=False) # lxml.etree only!
b'<br/>'

 If you want to read only the text, i.e. without any intermediate tags, you have to recursively concatenate all text and tail attributes in the correct order. Again, the tostring() function comes to the rescue, this time using the method keyword:

>>> etree.tostring(html, method="text")
b'TEXTTAIL'
原文地址:https://www.cnblogs.com/bluescorpio/p/3131184.html