python模块之HTMLParser之穆雪峰的案例(理解其用法原理)

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#python模块之HTMLParser之穆雪峰的案例(理解其用法原理)
#http://www.cnblogs.com/xiaowuyi/archive/2012/10/15/2721658.html



#常见做法:首先,我们需要定义一个新的HTMLParser类,以覆盖handle_starttag()方法,我们将使用这个方法来显示所有标签的HRef属性值。
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):

    
    def handle_starttag(self, tag, attrs):
        #print('<开始标签:%s>' % tag)
        #print '---------some img--------'
        if tag=='img':
            #print attrs#[('src', 'python-logo.png'), ('alt', 'The Python logo')]
            for k ,v in attrs:
                print k,v
        else:
            pass
    def handle_endtag(self, tag):
        print('<结束标签:/%s>' % tag)

    def handle_startendtag(self, tag, attrs):
        print('<%s/>' % tag)

    def handle_data(self, data):
        print 'data:',data

    def handle_comment(self, data):
        print '<!-- -->',data
        
    def handle_decl(self, decl):
        print '文档类型声明:',decl
    '''
    def handle_entityref(self, name):#处理一些特殊字符,以&开头的
        print('&%s;' % name)

    def handle_charref(self, name):#处理特殊字符串,就是以&#开头的,一般是内码表示的字符
        print('&#%s;' % name)
    '''
parser = MyHTMLParser()
content=''''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
<html>
    <head>
    </head>
        <body>
            <p>Some
                <a href="#">html</a> tutorial...<br>END
                <!-- i am Notes Content-->
                <img src="python-logo.png" alt="The Python logo">
            </p>
        </body>
</html>
'''
import urllib
html=urllib.urlopen('http://www.163.com').read()
#parser.feed(html)
parser.feed(content)
parser.close()
原文地址:https://www.cnblogs.com/dengyg200891/p/4983835.html