zoukankan      html  css  js  c++  java
  • #小练习 使用字典保存HTMLParser解析的数据 分类: python 小练习 HTMLParser 2013-11-08 20:51 574人阅读 评论(0) 收藏

    #coding:utf-8

    import HTMLParser

    class myhp(HTMLParser.HTMLParser):
        def __init__(self):
            HTMLParser.HTMLParser.__init__(self)
            self.d={}
            self.tag=None
            self.content=None
        def handle_starttag(self,tag,attr):
            #注意:tag不区分大小写,此时也可以解析 <A 标签
            if tag=='a':
                for href,link in attr:
                    if href.lower()=="href":
                        self.tag='a'
                        self.content=link

        def handle_data(self,data):
            if self.tag=='a' and len(data.strip()):
                self.d[data.strip()] =self.content

        # 遇到 </a ,设置self.tag =None
        def handle_endtag(self,tag):
            if tag=='a':
                self.tag=None





    if __name__ == "__main__":
        html_code='''
        <a href="www.google.com"> goolge.com </a>
        <AB href="www.sohu.com.cn"> sohu.com </a>
        <A Href="www.pythonclub.org">PythonClub </a>
        <A HREF='www.sina.com.cn'> sina </a>
        '''
        m = myhp()
        m.feed(html_code)
        print m.d
        m.close()

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    css 样式合集
    java-TheadPoolExecutor
    ConcurrentHashMap
    java线程
    hadoop 笔记
    java中的锁
    关闭防火墙
    hadoop集群搭建
    ssh免密码登录
    pyrhon 技巧 解析pymysql查询结果,取mysql其中的某一列数据 zip解压
  • 原文地址:https://www.cnblogs.com/think1988/p/4628023.html
Copyright © 2011-2022 走看看