【简记】用lxml解析html

来源:互联网 发布:小甲鱼c语言新版 编辑:程序博客网 时间:2024/06/05 19:59

本文节选自:http://www.cnblogs.com/descusr/archive/2012/06/20/2557075.html

演示一段获取页面链接代码示例:

#coding=utf-8

from lxml import etree

html = '''

<html>
  <head>
    <meta name="content-type" content="text/html; charset=utf-8" />
    <title>友情链接查询 - 站长工具</title>
    <!-- uRj0Ak8VLEPhjWhg3m9z4EjXJwc -->
    <meta name="Keywords" content="友情链接查询" />
    <meta name="Description" content="友情链接查询" />

  </head>
  <body>
    <h1 class="heading">Top News</h1>
    <p style="font-size: 200%">World News only on this page</p>
    Ah, and here's some more text, by the way.
    <p>... and this is a parsed fragment ...</p>

    <a href="http://www.cydf.org.cn/" rel="nofollow" target="_blank">青少年发展基金会</a> 
    <a href="http://www.4399.com/flash/32979.htm" target="_blank">洛克王国</a> 
    <a href="http://www.4399.com/flash/35538.htm" target="_blank">奥拉星</a> 
    <a href="http://game.3533.com/game/" target="_blank">手机游戏</a>
    <a href="http://game.3533.com/tupian/" target="_blank">手机壁纸</a>
    <a href="http://www.4399.com/" target="_blank">4399小游戏</a> 
    <a href="http://www.91wan.com/" target="_blank">91wan游戏</a>

  </body>
</html>

'''

page = etree.HTML(html.lower().decode('utf-8'))

hrefs = page.xpath(u"//a")

for href in hrefs:

  print href.attrib

 

打印出的结果为:

{'href': 'http://www.cydf.org.cn/', 'target': '_blank', 'rel': 'nofollow'}
{'href': 'http://www.4399.com/flash/32979.htm', 'target': '_blank'}
{'href': 'http://www.4399.com/flash/35538.htm', 'target': '_blank'}
{'href': 'http://game.3533.com/game/', 'target': '_blank'}
{'href': 'http://game.3533.com/tupian/', 'target': '_blank'}
{'href': 'http://www.4399.com/', 'target': '_blank'}
{'href': 'http://www.91wan.com/', 'target': '_blank'}

如果要取得<a></a>之间的内容,

for href in hrefs:

  print href.text

结果为:

青少年发展基金会
洛克王国
奥拉星
手机游戏
手机壁纸
4399小游戏
91wan游戏

 

  使用lxml前注意事项:先确保html经过了utf-8解码,即code = html.decode('utf-8', 'ignore'),否则会出现解析出错情况。因为中文被编码成utf-8之后变成 '/u2541' 之类的形式,lxml一遇到 “/”就会认为其标签结束。

 【转载补充】这里应该是确保html转化为unicode编码,如果html是采用gbk编码的则使用decode('gbk')方法

  XPATH基本上是用一种类似目录树的方法来描述在XML文档中的路径。比如用“/”来作为上下层级间的分隔。第一个“/”表示文档的根节点(注意,不是指文档最外层的tag节点,而是指文档本身)。比如对于一个HTML文件来说,最外层的节点应该是"/html"。

定位某一个HTML标签,可以使用类似文件路径里的绝对路径,如page.xpath(u"/html/body/p"),它会找到body这个节点下所有的p标签;也可以使用类似文件路径里的相对路径,可以这样使用:page.xpath(u"//p"),它会找到整个html代码里的所有p标签:

    <p style="font-size: 200%">World News only on this page</p>
    Ah, and here's some more text, by the way.
    <p>... and this is a parsed fragment ...</p>

注意:XPATH返回的不一定就是唯一的节点,而是符合条件的所有节点。如上所示,只要是body里的p标签,不管是body的第一级节点,还是第二级,第三级节点,都会被取出来。

0 0