python的lxml模块

简介:

环境:python2.7

安装lxml模块

1
pip  install  lxml

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
< 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 >
1
2
3
4
5
#读取文件里的内容
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模块,故没好好写,下面是我微信二维码


2852890398f48fee0c11bb77eaaf87da.jpg



本文转自 天道酬勤VIP 51CTO博客,原文链接:http://blog.51cto.com/tdcqvip/1976612

相关文章
|
17天前
|
机器学习/深度学习 存储 Python
|
1天前
|
Python
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存在,该函数对路径进行检查,存在则返回True,不存在则返回False。示例代码展示了如何检查&#39;example.txt&#39;文件是否存在并相应打印消息。此外,`os.path.isfile()`用于确认路径是否为文件,仅当是文件时返回True,否则返回False,同样配以示例说明其用法。
8 2
|
2天前
|
Python
【Python进阶(五)】——模块搜索及工作目录
【Python进阶(五)】——模块搜索及工作目录
|
3天前
|
Python Windows
python中的异常与模块
python中的异常与模块
9 1
|
13天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;city&quot;: &quot;New York&quot;}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
17 1
|
14天前
|
Python
Python实现压缩解压---tarfile模块详解
Python实现压缩解压---tarfile模块详解
|
14天前
|
Linux Python Windows
Python中time和datetime模块详解
Python中time和datetime模块详解
|
14天前
|
存储 Linux 数据安全/隐私保护
python的压缩模块zipfile详解
python的压缩模块zipfile详解
|
14天前
|
Linux Python Windows
python的os模块详细解读(二)
python的os模块详细解读(二)
|
14天前
|
移动开发 Linux Shell
python的os模块详细解读(一)
python的os模块详细解读(一)
python的os模块详细解读(一)