数据提取(二):xpath - lxml从字符串和文件中解析html代码 etree.html(),etree.tostring(),etree.parse(),etree.HTMLParser()

一、lxml库简述

lxml库是一个HTML、XML的解析器,主要功能是如何解析和提取HTML、XML数据。它和正则一样是用 C 实现的,是一款高性能的 Python HTML/XML 解析器,可以利用之前学习的XPath语法,来快速的定位特定元素以及节点信息。

lxml python 官方文档:http://lxml.de/index.html

需要安装C语言库,可使用 pip 安装:pip install lxml

二、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>  <!--&#27880;&#24847; &#36825;&#37324;&#23569;&#20102;&#19968;&#20010;<li>&#26631;&#31614;-->\n     </li></ul>\n </div>\n</body></html>'

<html>
  • 16
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值