zoukankan      html  css  js  c++  java
  • 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'
    
  • 相关阅读:
    Python 两个list合并成一个字典
    python 取列表(数组)偶数和奇数位置的值
    爬虫-Xpath语法笔记-转载
    详解Python requests 超时和重试的方法-转载
    6种负载均衡算法-转载
    python学习点滴记录-Day22
    python学习点滴记录-Day21-项目
    python学习点滴记录-Day20(分页、cookie/session、ajax)
    vimrc
    使用 find 命令实现高级排除需求
  • 原文地址:https://www.cnblogs.com/bluescorpio/p/3131184.html
Copyright © 2011-2022 走看看