首页 > Web开发 > 详细

HTMLParser 解析HTML

时间:2016-01-12 21:11:00      阅读:146      评论:0      收藏:0      [点我收藏+]
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>‘‘‘)

 

HTMLParser 解析HTML

原文:http://www.cnblogs.com/jzm17173/p/5125458.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!