您的位置:首页 > Web前端 > HTML

HTMLParser 解析HTML

2016-01-12 20:00 330 查看
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>''')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: