Python基础 HTMLParser

来源:互联网 发布:qt tcp编程 编辑:程序博客网 时间:2024/05/21 07:48

解析该HTML页面

编写一个搜索引擎
1. 第一步是用爬虫把目标网站的页面抓下来
2. 第二步就是解析该HTML页面

运行示例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# Python基础 HTMLParserdata ='''<html>    <head>        <!-- head -->    </head>    <body>        <!-- test html parser -->    </body></html>'''from html.parser import HTMLParserfrom html.entities import name2codepointclass 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>