HTMLParser 主要包含以下几个方法:
class MyHTMLParser1(HTMLParser):
def handle_starttag(self, tag, attrs):
#遭遇到开始标签的时候需要做哪些action
def handle_endtag(self, tag):
#遭遇到结束标签的时候需要做哪些action
#遭遇到开始标签的时候需要做哪些action
def handle_endtag(self, tag):
#遭遇到结束标签的时候需要做哪些action
def handle_startendtag(self, tag, attrs):
#遭遇到类似 <img ... />这种格式的xhtml格式的
#遭遇到类似 <img ... />这种格式的xhtml格式的
def handle_data(self, data):
#遭遇到html中的数据的时候需要做哪些action
#遭遇到html中的数据的时候需要做哪些action
def handle_comment(self, data):
#遭遇到备注信息时候需要做哪些action
#遭遇到备注信息时候需要做哪些action
def handle_entityref(self, name):
#遭遇引用名称时候需要做哪些action
#遭遇引用名称时候需要做哪些action
def handle_charref(self, name):
#遭遇到特殊字符的时候需要做哪些action
#遭遇到特殊字符的时候需要做哪些action
直接上代码:
from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint
class MyHTMLParser1(HTMLParser):
def handle_starttag(self, tag, attrs):
print('handle_start tag is <%s>,attrs is %s ,attrs len is %s' % (tag,attrs,len(attrs)))
def handle_endtag(self, tag):
print('handl_endtag is
' % tag)
def handle_startendtag(self, tag, attrs):
print('handle_startend tag is <%s/>' % tag)
def handle_data(self, data):
print('handle_data is %s' % data)
def handle_comment(self, data):
print('
')
def handle_entityref(self, name):
print('speacial is &%s;' % name)
def handle_charref(self, name):
print('&#%s;' % name)
class MyHTMLParser(HTMLParser):
a = False
l = []
def handle_starttag(self, tag, attrs):
if tag =='time':
self.a = True
def handle_data(self, data):
if self.a == True:
self.l.append(data)
print self.l
'''def handle_entityref(self, name):
if name =='ndash':
#print '-'
return '-' '''
parser = MyHTMLParser1()
parser.feed('<script src="/static/js/libs/modernizr.js"></script>')empty
运行结果: