HTMLParser是python用来解析html的模块,它可以分析出html里面的标签、数据等。
HTMLParser采用的是一种事件驱动的模式,当HTMLParser找到一个特定的标记时,它会去调用一个用户定义的函数,以此来通知程序处理。它主要的用户回调函数的命名都是以handler_开头的,都是HTMLParser的成员函数。
handle_startendtag 处理开始标签和结束标签
handle_starttag 处理开始标签,比如<xx>
handle_endtag 处理结束标签,比如</xx>
handle_charref 处理特殊字符串,就是以&#开头的,一般是内码表示的字符
handle_entityref 处理一些特殊字符,以&开头的,比如
handle_data 处理数据,就是<xx>data</xx>中间的那些数据
handle_comment 处理注释
handle_decl 处理<!开头的,比如<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
handle_pi 处理形如<?instruction>的东西
举例:
#!usr/bin/env python3
# -*- coding:utf-8 -*-
from html.parser import HTMLParser
from html.entities import name2codepoint
class MyHTMLParser2(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.flag=None
def handle_starttag(self,tag,attrs):
if tag=='h3' and attrs.__contains__(('class','event-title')):
print('\n\n会议主题:',end='')
self.flag=True #在需要打印的块中设置标识
elif tag=='time':
print('\n会议时间:',end='')
self.flag=True
elif tag=='span' and attrs.__contains__(('class','event-location')):
print('\n会议地址:',end='')
self.flag=True
def handle_endtag(self,tag):
if tag in('h3','time','span'):
self.flag=None
#print('</%s>' % tag)
def handle_startendtag(self,tag,attrs):
#print('<%s/>' % tag)
pass
def handle_data(self,data):
#print('----------->%s'%data.strip())
if self.flag: #判断是需要的值才打印
print('%s' % data,end='') #末尾不换行
def hangle_comment(self,data):
#print('<!-- -->')
pass
def handle_entityref(self,name):
#print('====>%s' % name)
if name=='ndash':
print('至',end='')
else:
pass
def handle_charref(self,name):
#print('&#%s;' % name)
pass
with open('python_meeting.xml','rb') as f:
s=f.read()
parser=MyHTMLParser2()
parser.feed(str(s))
会议主题:PyCon Ghana 2018
会议时间:10 Aug. \xe2\x80\x93 12 Aug. 2018
会议地址:Accra, Ghana
会议主题:PyData Delhi 2018
会议时间:11 Aug. \xe2\x80\x93 13 Aug. 2018
会议地址:New Delhi, India
会议主题:PyCon Korea 2018
会议时间:15 Aug. \xe2\x80\x93 20 Aug. 2018
会议地址:Seoul, South Korea
会议主题:PyBay 2018
会议时间:16 Aug. \xe2\x80\x93 20 Aug. 2018
会议地址:San Francisco, CA, USA
会议主题:PyCon PL 2018
会议时间:23 Aug. \xe2\x80\x93 27 Aug. 2018
会议地址:Ossa, Poland
会议主题:Flask Conference
会议时间:24 Aug. \xe2\x80\x93 26 Aug. 2018
会议地址:S\xc3\xa3o Paulo, Brazil