HTMLParser, a simple lib as html/xhtml parser
官方解释:
This module defines a class HTMLParser which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.Unlike the parser in htmllib, this parser is not based on the SGML parser in sgmllib.
An HTMLParser instance is fed HTML data and calls handler methodswhen start tags, end tags, text, comments, and other markup elements areencountered. The user should subclass HTMLParser and override its methods to implement the desired behavior.
The HTMLParser class is instantiated without arguments.
Unlike the parser in htmllib, this parser does not check that end tags match start tags or call the end-tag handler for elements which are closedimplicitly by closing an outer element.
An exception is defined as well:
HTMLParser is able to handle broken markup, but in some cases it might raise this exception when it encounters an error while parsing.This exception provides three attributes: msg is a briefmessage explaining the error, lineno is the number of the line onwhich the broken construct was detected, and offset is the number ofcharacters into the line at which the construct starts.
#!/usr/bin/python #a simple htmlparser demo from HTMLParser import HTMLParser class SimpleParser(HTMLParser): def handle_starttag(self,tag,attr): print tag def handle_endtag(self,tag): print tag def handle_data(self,data): print data simpleparser = SimpleParser() simpleparser.feed("<title></title>")
的html标记外,还同时用
This method is called to process a named character reference of the form&name; (e.g. >), where name is a general entity reference(e.g. ‘gt‘).
下面是代码:
#!/usr/bin/env python from HTMLParser import HTMLParser #handle entity like & from htmlentitydefs import entitydefs import sys class TitleParser(HTMLParser): def __init__(self): self.taglevels = [] #处理title ul li 只有开始无结束标记的情况 self.handledtags = ['title', 'ul', 'li'] self.processing = None HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): if len(self.taglevels) and self.taglevels[-1] == tag: self.handle_endtag(tag) self.taglevels.append(tag) if tag in self.handledtags: self.data = '' self.processing = tag if tag == 'ul': #do print def handle_data(self, data): if self.processing: self.title += data def handle_endtag(self, tag): if not tag in self.taglevels: return while len(self.taglevels): starttag = self.taglevels.pop() if starttag in self.handledtags: self.finishprocessing(starttag) if starttag == tag: break def cleanse(self): self.data = re.sub('\s+', ' ', self.data) def finishprocessing(self, tag): self.cleanse() if tag == 'title' and tag == self.processing: print "Dom title", self.data elif tag == 'ul': print "List ended" elif tag == 'li' and tag == self.processing: print "List item", self.data self.processing = None def gettitle(self): return self.title #处理特殊值,如果在映射表中有对应的,即采用映射的值,否则为字面值 def handle_entityref(self, name): if entitydefs.has_key(name): self.handle_data(entitydefs[name]) else: self.handle_data('&' + name + ';') def handle_charref(self, name): try: charnum = int(name) except ValueError: return if charnum < 1 or charnum > 255: return self.handle_data(chr(charnum)) fd = open(sys.argv[1]) tp = TitleParser() tp.feed(fd.read()) print tp.gettitle()
python 解析html基础 HTMLParser库,方法,及代码实例,布布扣,bubuko.com
python 解析html基础 HTMLParser库,方法,及代码实例
原文:http://blog.csdn.net/crmiv/article/details/27387797