赞
踩
lxml库是一个HTML、XML的解析器,主要功能是如何解析和提取HTML、XML数据。它和正则一样是用 C 实现的,是一款高性能的 Python HTML/XML 解析器,可以利用之前学习的XPath语法,来快速的定位特定元素以及节点信息。
lxml python 官方文档:http://lxml.de/index.html
需要安装C语言库,可使用 pip 安装:pip install lxml
(1)从字符串中解析HTML代码:etree.html(str)
函数定义: HTML(text, parser=None, base_url=None) Parses an HTML document from a string constant. Returns the root node (or the result returned by a parser target). 作用: 解析HTML代码的时候,如果HTML代码不规范,自动进行补全 利用etree.HTML(string),将字符串解析为HTML文档 利用etree.tostring(html) 按字符串将HTML文档序列化为bytes类型,可通过decode('utf-8')解码为str类型 etree.tostring()函数详解稍后给出 返回值:返回一个<class 'lxml.etree._Element'>对象 参数列表: parser:主要是重写overrie该函数的解析机制时传入,一般不用 base_url:为该生成的html文档设置url,以此来支持查找外部实体时可使用相对路径 The ``base_url`` keyword allows setting a URL for the document when parsing from a file-like object. This is needed when looking up external entities (DTD, XInclude, ...) with relative paths. from lxml import etree text = ''' <div> <ul> <li class="item-0"><a href="link1.html">first item</a></li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-inactive"><a href="link3.html">third item</a></li> <li class="item-1"><a href="link4.html">fourth item</a></li> <li class="item-0"><a href="link5.html">fifth item</a> <!--注意 这里少了一个<li>标签--> </ul> </div> ''' html = etree.HTML(text) print(type(html)) print(html) bytes_res = etree.tostring(html) print(bytes_res) str_res = etree.tostring(html).decode('utf-8') print(str_res)
运行结果
<Element html at 0x3197b98>
<class 'lxml.etree._Element'>
b'<html><body><div>\n <ul>\n <li class="item-0"><a href="link1.html">first item</a></li>\n <li class="item-1"><a href="link2.html">second item</a></li>\n <li class="item-inactive"><a href="link3.html">third item</a></li>\n <li class="item-1"><a href="link4.html">fourth item</a></li>\n <li class="item-0"><a href="link5.html">fifth item</a> <!--注意 这里少了一个<li>标签-->\n </li></ul>\n </div>\n</body></html>'
<html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。