lxml库
lxml 是 一个HTML/XML的解析器,主要的功能是如何解析和提取HTML/XML 数据。
lxml和正则一样,也是用 C 实现的,是一款高性能的 Python HTML/XML 解析器,我们可以利用之前学习的XPath语法,来快速的定位特定元素以及节点信息。
lxml python 官方文档:http://lxml.de/index.html
win系统安装不了的可以在这里找:https://www.lfd.uci.edu/~gohlke/pythonlibs/
需要安装C语言库,可使用 pip 安装:pip install lxml
基本使用:
我们可以利用他来解析HTML代码,并且在解析HTML代码的时候,如果HTML代码不规范,他会自动的进行补全。
from lxml import etree html = etree.HTML(text) result = etree.tostring(html) print(result)
从文件中读取html代码:
除了直接使用字符串进行解析,lxml还支持从文件中读取内容。
from lxml import etree # 读取外部文件 hello.html html = etree.parse('hello.html') result = etree.tostring(html, pretty_print=True) print(result)
案例
from lxml import etree html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ #将字符串解析为html文档 html = etree.HTML(html_doc) #按字符串序列化html文档 print(html) result = etree.tostring(html).decode('utf-8') print(result)