HTMLParser 解析HTML

时间:2022-01-02 12:11:43
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>''')