Python 2_7 Html Parser

https://docs.python.org/2/library/htmlparser.html

Note
The HTMLParser module has been renamed to in Python
3. The 2to3 tool will automatically adapt imports when converting
your sources to Python 3.
New in version 2. 2.
Source code: Lib/
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.
class MLParser¶
An HTMLParser instance is fed HTML data and calls handler methods
when start tags, end tags, text, comments, and other markup elements are
encountered. 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 closed
implicitly by closing an outer element.
An exception is defined as well:
exception MLParseError¶
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 brief
message explaining the error, lineno is the number of the line on
which the broken construct was detected, and offset is the number of
characters into the line at which the construct starts.
19. 1. Example HTML Parser Application¶
As a basic example, below is a simple HTML parser that uses the
HTMLParser class to print out start tags, end tags and data
as they are encountered:
from HTMLParser import HTMLParser
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print “Encountered a start tag:”, tag
def handle_endtag(self, tag):
print “Encountered an end tag:”, tag
def handle_data(self, data):
print “Encountered some data:”, data
# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
(‘Test

Parse me!

‘)
The output will then be:
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data: Test
Encountered an end tag: title
Encountered an end tag: head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data: Parse me!
Encountered an end tag: h1
Encountered an end tag: body
Encountered an end tag: html
19. 2. HTMLParser Methods¶
HTMLParser instances have the following methods:
(data)¶
Feed some text to the parser. It is processed insofar as it consists of
complete elements; incomplete data is buffered until more data is fed or
close() is called. data can be either unicode or
str, but passing unicode is advised.
()¶
Force processing of all buffered data as if it were followed by an end-of-file
mark. This method may be redefined by a derived class to define additional
processing at the end of the input, but the redefined version should always call
the HTMLParser base class method close().
Reset the instance. Loses all unprocessed data. This is called implicitly at
instantiation time.
Return current line number and offset.
t_starttag_text()¶
Return the text of the most recently opened start tag. This should not normally
be needed for structured processing, but may be useful in dealing with HTML “as
deployed” or for re-generating input with minimal changes (whitespace between
attributes can be preserved, etc. ).
The following methods are called when data or markup elements are encountered
and they are meant to be overridden in a subclass. The base class
implementations do nothing (except for handle_startendtag()):
HTMLParser. handle_starttag(tag, attrs)¶
This method is called to handle the start of a tag (e. g.

).
The tag argument is the name of the tag converted to lower case. The attrs
argument is a list of (name, value) pairs containing the attributes found
inside the tag’s <> brackets. The name will be translated to lower case,
and quotes in the value have been removed, and character and entity references
have been replaced.
For instance, for the tag ‘)
Decl: DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4. 01//EN” ”
Parsing an element with a few attributes and a title:
>>> (‘The Python logo‘)
Start tag: img
attr: (‘src’, ”)
attr: (‘alt’, ‘The Python logo’)
>>>
>>> (‘

Python

‘)
Start tag: h1
Data: Python
End tag: h1
The content of script and style elements is returned as is, without
further parsing:
>>> (‘

‘)
Start tag: style
attr: (‘type’, ‘text/css’)
Data: #python { color: green}
End tag: style
>>> (‘‘)
Start tag: script
attr: (‘type’, ‘text/javascript’)
Data: alert(“hello! “);
End tag: script
Parsing comments:
>>> (‘‘… ‘IE-specific content‘)
Comment: a comment
Comment: [if IE 9]>IE-specific content‘):
>>> (‘>>>’)
Named ent: >
Num ent: >
Feeding incomplete chunks to feed() works, but
handle_data() might be called more than once:
>>> for chunk in [‘buff’, ‘ered ‘, ‘text‘]:… (chunk)…
Start tag: span
Data: buff
Data: ered
Data: text
End tag: span
Parsing invalid HTML (e. unquoted attributes) also works:
>>> (‘

tag soup

‘)
Start tag: p
Start tag: a
attr: (‘class’, ‘link’)
attr: (‘href’, ‘#main’)
Data: tag soup
End tag: p
End tag: a
19.1. HTMLParser — Simple HTML and XHTML parser

19.1. HTMLParser — Simple HTML and XHTML parser

Note
The HTMLParser module has been renamed to in Python
3. 0. The 2to3 tool will automatically adapt imports when converting
your sources to 3. 0.
New in version 2. 2.
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.
class MLParser¶
The HTMLParser class is instantiated without arguments.
An HTMLParser instance is fed HTML data and calls handler functions when tags
begin and end. The HTMLParser class is meant to be overridden by the
user to provide a desired behavior.
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 closed
implicitly by closing an outer element.
An exception is defined as well:
exception MLParseError¶
Exception raised by the HTMLParser class when it encounters an error
while parsing. This exception provides three attributes: msg is a brief
message explaining the error, lineno is the number of the line on which
the broken construct was detected, and offset is the number of
characters into the line at which the construct starts.
HTMLParser instances have the following methods:
()¶
Reset the instance. Loses all unprocessed data. This is called implicitly at
instantiation time.
(data)¶
Feed some text to the parser. It is processed insofar as it consists of
complete elements; incomplete data is buffered until more data is fed or
close() is called.
Force processing of all buffered data as if it were followed by an end-of-file
mark. This method may be redefined by a derived class to define additional
processing at the end of the input, but the redefined version should always call
the HTMLParser base class method close().
Return current line number and offset.
t_starttag_text()¶
Return the text of the most recently opened start tag. This should not normally
be needed for structured processing, but may be useful in dealing with HTML “as
deployed” or for re-generating input with minimal changes (whitespace between
attributes can be preserved, etc. ).
HTMLParser. handle_starttag(tag, attrs)¶
This method is called to handle the start of a tag. It is intended to be
overridden by a derived class; the base class implementation does nothing.
The tag argument is the name of the tag converted to lower case. The attrs
argument is a list of (name, value) pairs containing the attributes found
inside the tag’s <> brackets. The name will be translated to lower case,
and quotes in the value have been removed, and character and entity references
have been replaced. For instance, for the tag

19.1. HTMLParser — Simple HTML and XHTML parser

Python 2. 7. 13
Note
The HTMLParser module has been renamed to in Python
3. The 2to3 tool will automatically adapt imports when converting
your sources to Python 3.
New in version 2. 2.
Source code: Lib/
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.
class MLParser
An HTMLParser instance is fed HTML data and calls handler methods
when start tags, end tags, text, comments, and other markup elements are
encountered. 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 closed
implicitly by closing an outer element.
An exception is defined as well:
exception MLParseError
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 brief
message explaining the error, lineno is the number of the line on
which the broken construct was detected, and offset is the number of
characters into the line at which the construct starts.
19. 1. Example HTML Parser Application
As a basic example, below is a simple HTML parser that uses the
HTMLParser class to print out start tags, end tags and data
as they are encountered:
from HTMLParser import HTMLParser
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print “Encountered a start tag:”, tag
def handle_endtag(self, tag):
print “Encountered an end tag:”, tag
def handle_data(self, data):
print “Encountered some data:”, data
# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
(‘Test

Parse me!

‘)
The output will then be:
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data: Test
Encountered an end tag: title
Encountered an end tag: head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data: Parse me!
Encountered an end tag: h1
Encountered an end tag: body
Encountered an end tag: html
19. 2. HTMLParser Methods
HTMLParser instances have the following methods:
(data)
Feed some text to the parser. It is processed insofar as it consists of
complete elements; incomplete data is buffered until more data is fed or
close() is called. data can be either unicode or
str, but passing unicode is advised.
()
Force processing of all buffered data as if it were followed by an end-of-file
mark. This method may be redefined by a derived class to define additional
processing at the end of the input, but the redefined version should always call
the HTMLParser base class method close().
Reset the instance. Loses all unprocessed data. This is called implicitly at
instantiation time.
Return current line number and offset.
t_starttag_text()
Return the text of the most recently opened start tag. This should not normally
be needed for structured processing, but may be useful in dealing with HTML “as
deployed” or for re-generating input with minimal changes (whitespace between
attributes can be preserved, etc. ).
The following methods are called when data or markup elements are encountered
and they are meant to be overridden in a subclass. The base class
implementations do nothing (except for handle_startendtag()):
HTMLParser. handle_starttag(tag, attrs)
This method is called to handle the start of a tag (e. g.

).
The tag argument is the name of the tag converted to lower case. The attrs
argument is a list of (name, value) pairs containing the attributes found
inside the tag’s <> brackets. The name will be translated to lower case,
and quotes in the value have been removed, and character and entity references
have been replaced.
For instance, for the tag
‘)
Decl: DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4. 01//EN” ”
Parsing an element with a few attributes and a title:
>>> (‘The Python logo‘)
Start tag: img
attr: (‘src’, ”)
attr: (‘alt’, ‘The Python logo’)
>>>
>>> (‘

Python

‘)
Start tag: h1
Data: Python
End tag: h1
The content of script and style elements is returned as is, without
further parsing:
>>> (‘

‘)
Start tag: style
attr: (‘type’, ‘text/css’)
Data: #python { color: green}
End tag: style
>>> (‘‘)
Start tag: script
attr: (‘type’, ‘text/javascript’)
Data: alert(“hello! “);
End tag: script
Parsing comments:
>>> (‘‘… ‘IE-specific content‘)
Comment: a comment
Comment: [if IE 9]>IE-specific content‘):
>>> (‘>>>’)
Named ent: >
Num ent: >
Feeding incomplete chunks to feed() works, but
handle_data() might be called more than once:
>>> for chunk in [‘buff’, ‘ered ‘, ‘text‘]:… (chunk)…
Start tag: span
Data: buff
Data: ered
Data: text
End tag: span
Parsing invalid HTML (e. unquoted attributes) also works:
>>> (‘

tag soup

‘)
Start tag: p
Start tag: a
attr: (‘class’, ‘link’)
attr: (‘href’, ‘#main’)
Data: tag soup
End tag: p
End tag: a

Frequently Asked Questions about python 2_7 html parser

Leave a Reply

Your email address will not be published. Required fields are marked *