zoukankan      html  css  js  c++  java
  • python模块学习---HTMLParser(解析HTML文档元素)

    HTMLParser是Python自带的模块,使用简单,能够很容易的实现HTML文件的分析。

    本文主要简单讲一下HTMLParser的用法.


    使用时需要定义一个从类HTMLParser继承的类,重定义函数:
    handle_starttag( tag, attrs)
    handle_startendtag( tag, attrs)
    handle_endtag( tag)

    来实现自己需要的功能。

    tag是的html标签,attrs是 (属性,值)元组(tuple)的列表(list)。
    HTMLParser自动将tag和attrs都转为小写。

    下面给出的例子抽取了html中的所有链接:(在PYTHON3.3版本中)

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. from html.parser import HTMLParser  
    2. class MyHTMLParser(HTMLParser):   
    3.     def __init__(self):   
    4.         HTMLParser.__init__(self)   
    5.         self.links = []   
    6.     def handle_starttag(self, tag, attrs):   
    7.         #print "Encountered the beginning of a %s tag" % tag   
    8.         if tag == "a":   
    9.             if len(attrs) == 0:   
    10.                 pass   
    11.             else:   
    12.                 for (variable, value) in attrs:   
    13.                     if variable == "href":   
    14.                         self.links.append(value)   
    15.                      
    16. if __name__ == "__main__":   
    17.     html_code = """ <a href="www.google.com"> google.com</a> <A Href="www.pythonclub.org"> PythonClub </a> <A HREF = "www.sina.com.cn"> Sina </a> """   
    18.     hp = MyHTMLParser()   
    19.     hp.feed(html_code)   
    20.     hp.close()   
    21.     print(hp.links)  


    运行结果为:

    ['www.google.com', 'www.pythonclub.org', 'www.sina.com.cn']

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

    显示HTML中<a>标签之间的文字:

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. from html.parser import HTMLParser  
    2.   
    3. page ='''''<sada>啊啊啊</sada><a href="http://click.union.360buy.com/JdClick /?unionId=75" class="f1"  style="padding-left:13px; padding-right:14px">京东商城</a></td><td><a href="http://www.letao.com /?source=hao123" class="f1">乐淘网上鞋城</a></td><td><a href="http://www.lashou.com/cl_today/w_3001" class="f2">拉手团购</a></td><td><a href="http://www.amazon.cn/?tag=2009hao123famousdaohang" class="f2">亚马逊</a></td><td><a href="http://www.vancl.com/?source=hao123mp"  class="f1">凡客诚品</a></td><td><a href="http://reg.jiayuan.com/st/?id=3237&url=/st /main.php" class="f1">世纪佳缘'''  
    4.   
    5. class hp(HTMLParser):  
    6.     a_text = False  
    7.       
    8.     def handle_starttag(self,tag,attr):  
    9.         if tag == 'a':  
    10.             self.a_text = True  
    11.             #print (dict(attr))  
    12.               
    13.     def handle_endtag(self,tag):  
    14.         if tag == 'a':  
    15.             self.a_text = False  
    16.               
    17.     def handle_data(self,data):  
    18.         if self.a_text:  
    19.             print (data)  
    20.               
    21. yk = hp()  
    22. yk.feed(page)  
    23. yk.close()  


    运行结果如下:

    京东商城
    乐淘网上鞋城
    拉手团购
    亚马逊
    凡客诚品
    世纪佳缘

    注:在eclipse中的pydev中调试,记得中文编码问题,在项目中右键改编码为utf-8

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

    如果想抽取图形链接

    <img src='http://www.google.com/intl/zh-CN_ALL/images/logo.gif' />


    就要重定义 handle_startendtag( tag, attrs) 函数

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

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

  • 相关阅读:
    编译安装linux内核步骤
    怎样在github上协同开发
    在JSP里使用CKEditor和CKFinder
    tomcat结合nginx使用小结
    JAVA学习笔记——(五)
    JAVA学习笔记——(四)
    JAVA学习笔记——(三)
    JAVA学习笔记——(二)
    JAVA学习笔记——(一)
    ansible
  • 原文地址:https://www.cnblogs.com/mfryf/p/3691563.html
Copyright © 2011-2022 走看看