python中用lxml解析html
lxml,是python中用来处理xml和html的功能最丰富和易用的库。详情见:http://lxml.de/index.html。在windows下安装lxml,可以用easy_install工具,也可以直接安装二进制文件。为了方便,我选择直接用二进制方式安装。
二进制文件的下载页面:https://pypi.python.org/pypi/lxml/3.4.1
选择合适的版本,因我的系统是win7,64位,python版本为2.7,所以我选择如下lxml版本。
安装完成后,就可以开始python代码了:
import codecs
import sys
from lxml import etree
tree = etree.HTML(open('d:\\GitHub\\python27\\simple.html','r').read())
nodes = tree.xpath("//div[@id='name']")
print(nodes).text
用到的html文件:
<!DOCTYPE html>
<html>
<head>
<title>This is a simple html file</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<div id="container">
<div id="name" class="item">勇者面码</div>
<div id="sex">女</div>
<div id="borth">9.18</div>
</div>
</body>
</html>
用lxml来解析,不会因为文档头小写而解析失败。
页:
[1]