赞
踩
1. 解析html字符串。使用“lxml.etree.HTML( )”进行解析。etree.tostring( )方法可以将htmlelement元素转化成字符串,可以正常打印出来。示例代码如下:
- # --coding:utf-8-- #
- from lxml import etree
- text = """
- """
- htmlelement = etree.HTML(text)
- print etree.tostring(htmlelement, encoding="utf-8").decode("utf-8")
2. 解析html文件。使用“lxml.etree.parse( )”进行解析,该方法默认使用的是“XML”解析器,所以如果碰到不规范的html文件时就会解析错误,报错代码如下:
- # --coding:utf-8-- #
- from lxml import etree
- htmlelement = etree.parse("C:\\Users\\Administrator\\Desktop\\baidu.html")
- print etree.tostring(htmlelement, encoding="utf-8").decode("utf-8")
- D:\Python3\python27\python.exe
- lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: meta line 3 and head, line 3, column 87
-
- Process finished with exit code 1
这时就要自己创建html解析器,增加参数“parser”,示例代码如下:
- # --coding:utf-8-- #
- from lxml import etree
- parser = etree.HTMLParser(encoding="utf-8")
- htmlelement = etree.parse("C:\\Users\\Administrator\\Desktop\\baidu.html", parser=parser)
- print etree.tostring(htmlelement, encoding="utf-8").decode("utf-8")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。