This document defines a Htmlparser class as the basis for parsing HTML documents.
An instance of the Htmlparser class can store and invoke methods to process HTML tags and data.
We generally do what we want by creating a subclass of Htmlparser and then overriding its methods.
Htmlparser There are many ways, generally we only need to cover the following methods:
Htmlparser.handle_starttag (tag, attrs) #遇到一个开始标签时就会执行这个方法 #tag is the label that is encountered, Attrs Attrs is a list of (attributes, values) tuples (tuple) (list )。 Htmlparser.handle_endtag (tag) #遇到一个结束标签时就会执行这个方法 #tag is the label htmlparser.handle_data (data) encountered what #这个方法处理标签里面的内容 #data to encounter
Let's start with a basic example to see how this module works.
This example prints the start and end tags as well as the contents of the tags.
From Htmlparser import Htmlparser class Myhtmlparser (Htmlparser): def handle_starttag (self, Tag, attrs): print ' encountered start tag:%s '%tag def handle_endtag (self, tag): print ' encountered end tag:%s '%tag def handle_data (self, data): print ' encountered content:%s '%data m = Myhtmlparser () m.feed (' Output:
Encounter the start tag: H3 encountered content: Title three encountered end tag: h3
Let's examine what this example does. First we set up a htmlparser and so on, and covered it in a way.
At run time, it first encounters a start tag "< H3>", executes Htmlparser.handle_starttag (tag, attrs) method, prints out the start tag.
Then it encountered the contents of the label "title Three", the implementation of Htmlparser.handle_data (data), print out "title three."
Finally it encounters the end tag, executes Htmlparser.handle_endtag (tag), prints out the end tag.
From this example, you can quickly understand how to use this module to parse HTML.
Parsing HTML document elements using the Python module--htmlparser