当前位置:   article > 正文

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

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
运行结果
<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/1006240
推荐阅读