解析该HTML页面
编写一个搜索引擎
1. 第一步是用爬虫把目标网站的页面抓下来
2. 第二步就是解析该HTML页面
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 HTMLParser
data ='''<html>
<head>
<!-- head -->
</head>
<body>
<!-- test html parser -->
</body>
</html>'''
from html.parser import HTMLParser
from html.entities import name2codepoint
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
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(data)
运行结果
D:\PythonProject>python main.py
<html>
<head>
<!-- head -->
</head>
<body>
<!-- test html parser -->
</body>
</html>