zoukankan      html  css  js  c++  java
  • Python之HTML的解析(网页抓取一)

    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. 基本解析,找到开始和结束标签

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

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

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

    或:

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
      1. <span style="font-size:18px;">#coding:utf-8  
      2.   
      3. from  HTMLParser import HTMLParser  
      4. import urllib2  
      5.   
      6. class myparser(HTMLParser):  
      7.   
      8.     # 继承父类初始化方法,并添加一个tag属性  
      9.     def __init__(self):  
      10.         HTMLParser.__init__(self)  
      11.         self.tag = None  
      12.   
      13.     def handle_decl(self,decl):  
      14.         print u"声明:",decl  
      15.   
      16.     def handle_starttag(self,tag,attrs):  
      17.         print u"开始标签;",tag  
      18.   
      19.         # 判断是否是a开头的标签  
      20.         if tag=='a' and len(attrs):  
      21.             #设置 self.tag 标记  
      22.             self.tag='a'  
      23.             for href,link in attrs:  
      24.                 if href=='href':  
      25.                     print href+":"+link  
      26.   
      27.     def handle_endtag(self,tag):  
      28.         print u"结束标签:",tag  
      29.   
      30.     def handle_data(self,data):  
      31.         #处理 a 标签开头的数据  
      32.         if self.tag=='a':  
      33.             print u"数据内容:",data.decode("utf-8")  
      34.   
      35.     def handle_comment(self,comm):  
      36.         print u"注释:",comm  
      37.   
      38.   
      39. if __name__ == '__main__':  
      40.   
      41.     a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
      42.     <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>'  
      43.     m = myparser()  
      44.     m.feed(a)  
      45.   
      46.   
      47.   
      48.   
      49.   
      50. 结果:  
      51.   
      52. 声明: DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"  
      53. 开始标签; html  
      54. 开始标签; head  
      55. 注释: insert javaScript here!  
      56. 开始标签; title  
      57. 结束标签: title  
      58. 开始标签; body  
      59. 开始标签; a  
      60. href:http: //www.163.com  
      61. 数据内容: 链接到163  
      62. 结束标签: a  
      63. 开始标签; a  
      64. href:http: //www.baidu.com  
      65. 数据内容: 百度  
      66. 结束标签: a  
      67. 结束标签: body  
      68. 结束标签: html</span>  
  • 相关阅读:
    elasticsearch 6.x.x 获取客户端方法
    struts2+spring 配置404和500错误页面
    linux 部署redis集群 碰到的坑
    Linux下安装redis
    struts加载spring
    有关struts中DispatchAction的用法小结
    spring AOP原理
    struts2.0的工作原理?
    Spring MVC的实现原理
    spring 的单例模式
  • 原文地址:https://www.cnblogs.com/kungfupanda/p/4655247.html
Copyright © 2011-2022 走看看