发布时间:2019-07-15 10:45:51编辑:auto阅读(1392)
环境:python2.7
安装lxml模块
pip install lxml
例子:
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> </ul> </div> ''' html = etree.HTML(text) #这是一个地址 result = etree.tostring(html) #读出来源码,并且补全,如输出的《body》标签 print(result)
输出:
<html> <body> <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> </body> </html>
#读取文件里的内容 from lxml import etree html = etree.parse('hello.html') result = etree.tostring(html, pretty_print=True) print(result)
获取li标签里的东西
html = etree.parse('hello.html') print type(html) result = html.xpath('//li') print result print len(result) print type(result) print type(result[0]) |
参考文章:http://cuiqingcai.com/2621.html
说明:此篇博客仅仅是为了自己学习lxml模块,故没好好写,下面是我微信二维码
上一篇: Python re函数
下一篇: python rabbitmq no_
47483
45786
36783
34310
28955
25589
24436
19606
19096
17626
5458°
6041°
5557°
5632°
6558°
5370°
5370°
5877°
5850°
7163°