HTMLParser 类包含的方法学习笔记

HTMLParser 主要包含以下几个方法:
class MyHTMLParser1(HTMLParser):

    def handle_starttag(self, tag, attrs):
       #遭遇到开始标签的时候需要做哪些action
  
    def handle_endtag(self, tag):
      #遭遇到结束标签的时候需要做哪些action

    def handle_startendtag(self, tag, attrs):
      #遭遇到类似 <img ... />这种格式的xhtml格式的

    def handle_data(self, data):
        #遭遇到html中的数据的时候需要做哪些action

    def handle_comment(self, data):
          #遭遇到备注信息时候需要做哪些action

    def handle_entityref(self, name):
        #遭遇引用名称时候需要做哪些action

    def handle_charref(self, name):
        #遭遇到特殊字符的时候需要做哪些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

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值