http://blog.csdn.net/my2010sam/article/details/14526223

---------------------

对html的解析是网页抓取的基础,分析抓取的结果找到自己想要的内容或标签以达到抓取的目的。

HTMLParser是python用来解析html的模块。它可以分析出html里面的标签、数据等等,是一种处理html的简便途径。 HTMLParser采用的是一种事件驱动的模式,当HTMLParser找到一个特定的标记时,它会去调用一个用户定义的函数,以此来通知程序处理它主要的用户回调函数的命名都是以handler_开头的,都是HTMLParser的成员函数。当我们使用时,就从HTMLParser派生出新的类,然后重新定义这几个以handler_开头的函数即可。这几个函数包括:

  • handle_startendtag  处理开始标签和结束标签
  • handle_starttag     处理开始标签,比如<xx>   tag不区分大小写
  • handle_endtag       处理结束标签,比如</xx>
  • handle_charref      处理特殊字符串,就是以&#开头的,一般是内码表示的字符
  • handle_entityref    处理一些特殊字符,以&开头的,比如 &nbsp;
  • handle_data         处理数据,就是<xx>data</xx>中间的那些数据
  • handle_comment      处理注释
  • handle_decl         处理<!开头的,比如<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
  • handle_pi           处理形如<?instruction>的东西

def handle_starttag(self,tag,attr):
        #注意:tag不区分大小写,此时也可以解析 <A 标签

        # SGMLParser 会在创建attrs 时将属性名转化为小写。

        if tag=='a':
            for href,link in attr:
                if href.lower()=="href":

                        pass

 

1. 基本解析,找到开始和结束标签

  1. <span style="font-size:18px;">#coding:utf-8
  2. from HTMLParser import HTMLParser
  3. '''''
  4. HTMLParser的成员函数:
  5. handle_startendtag  处理开始标签和结束标签
  6. handle_starttag     处理开始标签,比如<xx>
  7. handle_endtag       处理结束标签,比如</xx>
  8. handle_charref      处理特殊字符串,就是以&#开头的,一般是内码表示的字符
  9. handle_entityref    处理一些特殊字符,以&开头的,比如
  10. handle_data         处理数据,就是<xx>data</xx>中间的那些数据
  11. handle_comment      处理注释
  12. handle_decl         处理<!开头的,比如<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
  13. handle_pi           处理形如<?instruction>的东西
  14. '''
  15. class myHtmlParser(HTMLParser):
  16. #处理<!开头的内容
  17. def handle_decl(self,decl):
  18. print 'Encounter some declaration:'+ decl
  19. def handle_starttag(self,tag,attrs):
  20. print 'Encounter the beginning of a %s tag' % tag
  21. def handle_endtag(self,tag):
  22. print 'Encounter the end of a %s tag' % tag
  23. #处理注释
  24. def handle_comment(self,comment):
  25. print 'Encounter some comments:' + comment
  26. if __name__=='__main__':
  27. a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\
  28. <html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a></body></html>'
  29. m=myHtmlParser()
  30. m.feed(a)
  31. m.close()
  32. 输出结果:
  33. Encounter some declaration:DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
  34. Encounter the beginning of a html tag
  35. Encounter the beginning of a head tag
  36. Encounter some comments:insert javaScript here!
  37. Encounter the beginning of a title tag
  38. Encounter the end of a title tag
  39. Encounter the beginning of a body tag
  40. Encounter the beginning of a a tag
  41. Encounter the end of a a tag
  42. Encounter the end of a body tag
  43. Encounter the end of a html tag</span>

2. 解析html的超链接和链接显示的内容  

  1. <span style="font-size:18px;">#coding:utf-8
  2. from HTMLParser import HTMLParser
  3. class myHtmlParser(HTMLParser):
  4. def __init__(self):
  5. HTMLParser.__init__(self)
  6. self.flag=None
  7. # 这里重新定义了处理开始标签的函数
  8. def handle_starttag(self,tag,attrs):
  9. # 判断标签<a>的属性
  10. if tag=='a':
  11. self.flag='a'
  12. for href,link in attrs:
  13. if href=='href':
  14. print "href:",link
  15. def handle_data(self,data):
  16. if self.flag=='a':
  17. print "data:",data.decode('utf-8')
  18. if __name__ == '__main__':
  19. a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\
  20. <html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a></body></html>'
  21. m=myHtmlParser()
  22. m.feed(a)
  23. m.close()
  24. 输出结果:
  25. href: http: //www.163.com
  26. data: 链接到163</span>

或:

    1. <span style="font-size:18px;">#coding:utf-8
    2. from  HTMLParser import HTMLParser
    3. import urllib2
    4. class myparser(HTMLParser):
    5. # 继承父类初始化方法,并添加一个tag属性
    6. def __init__(self):
    7. HTMLParser.__init__(self)
    8. self.tag = None
    9. def handle_decl(self,decl):
    10. print u"声明:",decl
    11. def handle_starttag(self,tag,attrs):
    12. print u"开始标签;",tag
    13. # 判断是否是a开头的标签
    14. if tag=='a' and len(attrs):
    15. #设置 self.tag 标记
    16. self.tag='a'
    17. for href,link in attrs:
    18. if href=='href':
    19. print href+":"+link
    20. def handle_endtag(self,tag):
    21. print u"结束标签:",tag
    22. def handle_data(self,data):
    23. #处理 a 标签开头的数据
    24. if self.tag=='a':
    25. print u"数据内容:",data.decode("utf-8")
    26. def handle_comment(self,comm):
    27. print u"注释:",comm
    28. if __name__ == '__main__':
    29. a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\
    30. <html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a><a href="http: //www.baidu.com">百度</a></body></html>'
    31. m = myparser()
    32. m.feed(a)
    33. 结果:
    34. 声明: DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
    35. 开始标签; html
    36. 开始标签; head
    37. 注释: insert javaScript here!
    38. 开始标签; title
    39. 结束标签: title
    40. 开始标签; body
    41. 开始标签; a
    42. href:http: //www.163.com
    43. 数据内容: 链接到163
    44. 结束标签: a
    45. 开始标签; a
    46. href:http: //www.baidu.com
    47. 数据内容: 百度
    48. 结束标签: a
    49. 结束标签: body
    50. 结束标签: html</span>

最新文章

  1. 在C#代码中应用Log4Net(一)简单使用Log4Net
  2. Webkit 文字和背景效果
  3. 自定义样式的select下拉框深入探索
  4. Unity Ragdoll(布娃娃系统)
  5. Robot Framework--04 工作区
  6. MVC5+EF6 简易版CMS(非接口) 第三章:数据存储和业务处理
  7. 函数fseg_create_general
  8. python命令行运行在win和Linux系统的不同
  9. Learn golang: Top 30 Go Tutorials for Programmers Of All Levels
  10. C++STL 容器比较
  11. 解决VS2010连接VSS时,Access to file&quot;\\***\rights.dat&quot; denied
  12. [转] iOS 动画库 Pop 和 Canvas 各自的优势和劣势是什么?
  13. linux创建新用户后shell无法自动补全命令或使用基本的shell命令
  14. SQL点点滴滴_查看所有存储过程或视图的位置及内容
  15. Centos为mysql开启binlog
  16. 【Web开发】一、页面布局
  17. shell习题第1题:每日一文件
  18. BZOJ1085_骑士精神_KEY
  19. synchronize 和volatile 实现共享变量在多线程中的可见性
  20. JavaScript知识点的总结

热门文章

  1. 利用Hadoop自带example实现wordCount
  2. C#的常量和变量以及其作用域和命名规范
  3. Python包管理工具setuptools之setup函数参数详解
  4. restfull知识点
  5. 【leetcode 105. 从前序与中序遍历序列构造二叉树】解题报告
  6. 初识Composer
  7. before和after兼容性测试
  8. HTTP的一些理解
  9. centos7网卡名称修改以及配置
  10. web.xml中如何设置配置文件的加载路径