您的位置:首页 > 编程语言 > Python开发

python模块学习---HTMLParser(解析HTML文档元素)

2017-02-26 16:34 691 查看
HTMLParser是Python自带的模块,使用简单,能够很容易的实现HTML文件的分析。

本文主要简单讲一下HTMLParser的用法.
转自:http://blog.csdn.net/hxsstar/article/details/17241709

使用时需要定义一个从类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
plain copy

 





from html.parser import HTMLParser  

class MyHTMLParser(HTMLParser):   

    def __init__(self):   

        HTMLParser.__init__(self)   

        self.links = []   

    def handle_starttag(self, tag, attrs):   

        #print "Encountered the beginning of a %s tag" % tag   

        if tag == "a":   

            if len(attrs) == 0:   

                pass   

            else:   

                for (variable, value) in attrs:   

                    if variable == "href":   

                        self.links.append(value)   

                     

if __name__ == "__main__":   

    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> """   

    hp = MyHTMLParser()   

    hp.feed(html_code)   

    hp.close()   

    print(hp.links)  

运行结果为:

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

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

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

[python] view
plain copy

 





from html.parser import HTMLParser  

  

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">世纪佳缘'''  

  

class hp(HTMLParser):  

    a_text = False  

      

    def handle_starttag(self,tag,attr):  

        if tag == 'a':  

            self.a_text = True  

            #print (dict(attr))  

              

    def handle_endtag(self,tag):  

        if tag == 'a':  

            self.a_text = False  

              

    def handle_data(self,data):  

        if self.a_text:  

            print (data)  

              

yk = hp()  

yk.feed(page)  

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>的东西
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python
相关文章推荐