设为首页 收藏本站
查看: 678|回复: 0

[经验分享] Python之HTML的解析(网页抓取一)

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-11-30 07:13:00 | 显示全部楼层 |阅读模式
  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

  • <span style="font-size:18px;">#coding:utf-8  

  • from HTMLParser import HTMLParser  
  • '''''
  • HTMLParser的成员函数:

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

  • '''  
  • class myHtmlParser(HTMLParser):  
  •     #处理<!开头的内容  
  •     def handle_decl(self,decl):  
  •         print 'Encounter some declaration:'+ decl  
  •     def handle_starttag(self,tag,attrs):  
  •         print 'Encounter the beginning of a %s tag' % tag  
  •     def handle_endtag(self,tag):  
  •         print 'Encounter the end of a %s tag' % tag  
  •     #处理注释  
  •     def handle_comment(self,comment):   
  •         print 'Encounter some comments:' + comment  


  • if __name__=='__main__':  
  •     a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\  
  •     <html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a></body></html>'  
  •     m=myHtmlParser()
  •     m.feed(a)
  •     m.close()

  • 输出结果:

  • Encounter some declaration:DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"  
  • Encounter the beginning of a html tag
  • Encounter the beginning of a head tag
  • Encounter some comments:insert javaScript here!
  • Encounter the beginning of a title tag
  • Encounter the end of a title tag
  • Encounter the beginning of a body tag
  • Encounter the beginning of a a tag
  • Encounter the end of a a tag
  • Encounter the end of a body tag
  • Encounter the end of a html tag</span>
  
  
  2. 解析html的超链接和链接显示的内容  
  



[python] view plaincopy

  • <span style="font-size:18px;">#coding:utf-8  
  • from HTMLParser import HTMLParser  
  • class myHtmlParser(HTMLParser):  

  •     def __init__(self):  
  •         HTMLParser.__init__(self)  
  •         self.flag=None  

  •     # 这里重新定义了处理开始标签的函数  
  •     def handle_starttag(self,tag,attrs):  
  •          # 判断标签<a>的属性  
  •         if tag=='a':  
  •             self.flag='a'  
  •             for href,link in attrs:  
  •                 if href=='href':  
  •                     print "href:",link  

  •     def handle_data(self,data):  
  •         if self.flag=='a':  
  •             print "data:",data.decode('utf-8')  

  • if __name__ == '__main__':  
  •     a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\  
  •     <html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a></body></html>'  
  •     m=myHtmlParser()
  •     m.feed(a)
  •     m.close()

  • 输出结果:

  • href: http: //www.163.com  
  • data: 链接到163</span>  
  
  
  或:
  



[python] view plaincopy

    • <span style="font-size:18px;">#coding:utf-8  

    • from  HTMLParser import HTMLParser  
    • import urllib2  

    • class myparser(HTMLParser):  

    •     # 继承父类初始化方法,并添加一个tag属性  
    •     def __init__(self):  
    •         HTMLParser.__init__(self)  
    •         self.tag = None  

    •     def handle_decl(self,decl):  
    •         print u"声明:",decl  

    •     def handle_starttag(self,tag,attrs):  
    •         print u"开始标签;",tag  

    •         # 判断是否是a开头的标签  
    •         if tag=='a' and len(attrs):  
    •             #设置 self.tag 标记  
    •             self.tag='a'  
    •             for href,link in attrs:  
    •                 if href=='href':  
    •                     print href+":"+link  

    •     def handle_endtag(self,tag):  
    •         print u"结束标签:",tag  

    •     def handle_data(self,data):  
    •         #处理 a 标签开头的数据  
    •         if self.tag=='a':  
    •             print u"数据内容:",data.decode("utf-8")  

    •     def handle_comment(self,comm):  
    •         print u"注释:",comm  


    • if __name__ == '__main__':  

    •     a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\  
    •     <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>'  
    •     m = myparser()
    •     m.feed(a)





    • 结果:

    • 声明: DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"  
    • 开始标签; html
    • 开始标签; head
    • 注释: insert javaScript here!
    • 开始标签; title
    • 结束标签: title
    • 开始标签; body
    • 开始标签; a
    • href:http: //www.163.com  
    • 数据内容: 链接到163  
    • 结束标签: a
    • 开始标签; a
    • href:http: //www.baidu.com
    • 数据内容: 百度
    • 结束标签: a
    • 结束标签: body
    • 结束标签: html</span>



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145072-1-1.html 上篇帖子: 2015/9/4 Python基础(8):映射和集合类型 下篇帖子: 【原创】Python第二章——字符串
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表