GitHub 博客园 Nanakon

HTMLParser 解析HTML

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        for (variable, value) in attrs:
            print(variable, value)
            if variable == 'class' and value == 'item':
                print(attrs)
                break
        print('<%s>' % tag)

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

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

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

    def handle_comment(self, data):
        print('<!--', data, '-->')

    def handle_entityref(self, name):
        print('&%s;' % name)

    def handle_charref(self, name):
        print('&#%s;' % name)

parser = MyHTMLParser()

parser.feed('''<html>
<head></head>
<body>
<!-- test html parser -->
    <p class=\"item\" id=\"item1\">Some <a href=\"#\">html</a> HTML tutorial...<br>END</p>
</body></html>''')

 

posted on 2016-01-12 20:00  jzm17173  阅读(170)  评论(0编辑  收藏  举报

导航

轻音