blob: 787ab4e386adfec9eca2ad938d6d5b3e721a1607 [file] [log] [blame]
Fred Draked995e112008-05-20 06:08:38 +00001
2:mod:`HTMLParser` --- Simple HTML and XHTML parser
3==================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00004
Fred Drake20b56602008-05-17 21:23:02 +00005.. module:: HTMLParser
Georg Brandl8ec7f652007-08-15 14:28:01 +00006 :synopsis: A simple parser that can handle HTML and XHTML.
7
Fred Drake20b56602008-05-17 21:23:02 +00008.. note::
Georg Brandl3682dfe2008-05-20 07:21:58 +00009
10 The :mod:`HTMLParser` module has been renamed to :mod:`html.parser` in Python
11 3.0. The :term:`2to3` tool will automatically adapt imports when converting
12 your sources to 3.0.
Fred Drake20b56602008-05-17 21:23:02 +000013
Georg Brandl8ec7f652007-08-15 14:28:01 +000014
15.. versionadded:: 2.2
16
17.. index::
18 single: HTML
19 single: XHTML
20
Éric Araujo29a0b572011-08-19 02:14:03 +020021**Source code:** :source:`Lib/HTMLParser.py`
22
23--------------
24
Georg Brandl8ec7f652007-08-15 14:28:01 +000025This module defines a class :class:`HTMLParser` which serves as the basis for
26parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
27Unlike the parser in :mod:`htmllib`, this parser is not based on the SGML parser
28in :mod:`sgmllib`.
29
30
31.. class:: HTMLParser()
32
33 The :class:`HTMLParser` class is instantiated without arguments.
34
Fred Drakecb51d842008-05-17 21:14:05 +000035 An :class:`HTMLParser` instance is fed HTML data and calls handler functions when tags
Georg Brandl8ec7f652007-08-15 14:28:01 +000036 begin and end. The :class:`HTMLParser` class is meant to be overridden by the
37 user to provide a desired behavior.
38
39 Unlike the parser in :mod:`htmllib`, this parser does not check that end tags
40 match start tags or call the end-tag handler for elements which are closed
41 implicitly by closing an outer element.
42
43An exception is defined as well:
44
45
46.. exception:: HTMLParseError
47
48 Exception raised by the :class:`HTMLParser` class when it encounters an error
49 while parsing. This exception provides three attributes: :attr:`msg` is a brief
50 message explaining the error, :attr:`lineno` is the number of the line on which
51 the broken construct was detected, and :attr:`offset` is the number of
52 characters into the line at which the construct starts.
53
54:class:`HTMLParser` instances have the following methods:
55
56
57.. method:: HTMLParser.reset()
58
59 Reset the instance. Loses all unprocessed data. This is called implicitly at
60 instantiation time.
61
62
63.. method:: HTMLParser.feed(data)
64
65 Feed some text to the parser. It is processed insofar as it consists of
66 complete elements; incomplete data is buffered until more data is fed or
67 :meth:`close` is called.
68
69
70.. method:: HTMLParser.close()
71
72 Force processing of all buffered data as if it were followed by an end-of-file
73 mark. This method may be redefined by a derived class to define additional
74 processing at the end of the input, but the redefined version should always call
75 the :class:`HTMLParser` base class method :meth:`close`.
76
77
78.. method:: HTMLParser.getpos()
79
80 Return current line number and offset.
81
82
83.. method:: HTMLParser.get_starttag_text()
84
85 Return the text of the most recently opened start tag. This should not normally
86 be needed for structured processing, but may be useful in dealing with HTML "as
87 deployed" or for re-generating input with minimal changes (whitespace between
88 attributes can be preserved, etc.).
89
90
91.. method:: HTMLParser.handle_starttag(tag, attrs)
92
93 This method is called to handle the start of a tag. It is intended to be
94 overridden by a derived class; the base class implementation does nothing.
95
96 The *tag* argument is the name of the tag converted to lower case. The *attrs*
97 argument is a list of ``(name, value)`` pairs containing the attributes found
98 inside the tag's ``<>`` brackets. The *name* will be translated to lower case,
99 and quotes in the *value* have been removed, and character and entity references
100 have been replaced. For instance, for the tag ``<A
101 HREF="http://www.cwi.nl/">``, this method would be called as
102 ``handle_starttag('a', [('href', 'http://www.cwi.nl/')])``.
103
104 .. versionchanged:: 2.6
Fred Draked995e112008-05-20 06:08:38 +0000105 All entity references from :mod:`htmlentitydefs` are now replaced in the attribute
106 values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
108
109.. method:: HTMLParser.handle_startendtag(tag, attrs)
110
111 Similar to :meth:`handle_starttag`, but called when the parser encounters an
112 XHTML-style empty tag (``<a .../>``). This method may be overridden by
113 subclasses which require this particular lexical information; the default
114 implementation simple calls :meth:`handle_starttag` and :meth:`handle_endtag`.
115
116
117.. method:: HTMLParser.handle_endtag(tag)
118
119 This method is called to handle the end tag of an element. It is intended to be
120 overridden by a derived class; the base class implementation does nothing. The
121 *tag* argument is the name of the tag converted to lower case.
122
123
124.. method:: HTMLParser.handle_data(data)
125
126 This method is called to process arbitrary data. It is intended to be
127 overridden by a derived class; the base class implementation does nothing.
128
129
130.. method:: HTMLParser.handle_charref(name)
131
132 This method is called to process a character reference of the form ``&#ref;``.
133 It is intended to be overridden by a derived class; the base class
134 implementation does nothing.
135
136
137.. method:: HTMLParser.handle_entityref(name)
138
139 This method is called to process a general entity reference of the form
140 ``&name;`` where *name* is an general entity reference. It is intended to be
141 overridden by a derived class; the base class implementation does nothing.
142
143
144.. method:: HTMLParser.handle_comment(data)
145
146 This method is called when a comment is encountered. The *comment* argument is
147 a string containing the text between the ``--`` and ``--`` delimiters, but not
148 the delimiters themselves. For example, the comment ``<!--text-->`` will cause
149 this method to be called with the argument ``'text'``. It is intended to be
150 overridden by a derived class; the base class implementation does nothing.
151
152
153.. method:: HTMLParser.handle_decl(decl)
154
Georg Brandlc79d4322010-08-01 21:10:57 +0000155 Method called when an SGML ``doctype`` declaration is read by the parser.
156 The *decl* parameter will be the entire contents of the declaration inside
157 the ``<!...>`` markup. It is intended to be overridden by a derived class;
158 the base class implementation does nothing.
159
160
161.. method:: HTMLParser.unknown_decl(data)
162
163 Method called when an unrecognized SGML declaration is read by the parser.
164 The *data* parameter will be the entire contents of the declaration inside
Georg Brandlb6dc81d2011-03-21 08:55:16 +0100165 the ``<!...>`` markup. It is sometimes useful to be overridden by a
Georg Brandlc79d4322010-08-01 21:10:57 +0000166 derived class; the base class implementation throws an :exc:`HTMLParseError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000167
168
169.. method:: HTMLParser.handle_pi(data)
170
171 Method called when a processing instruction is encountered. The *data*
172 parameter will contain the entire processing instruction. For example, for the
173 processing instruction ``<?proc color='red'>``, this method would be called as
174 ``handle_pi("proc color='red'")``. It is intended to be overridden by a derived
175 class; the base class implementation does nothing.
176
177 .. note::
178
179 The :class:`HTMLParser` class uses the SGML syntactic rules for processing
180 instructions. An XHTML processing instruction using the trailing ``'?'`` will
181 cause the ``'?'`` to be included in *data*.
182
183
184.. _htmlparser-example:
185
186Example HTML Parser Application
187-------------------------------
188
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300189As a basic example, below is a simple HTML parser that uses the
190:class:`HTMLParser` class to print out start tags, end tags and data
191as they are encountered::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000192
Fred Draked995e112008-05-20 06:08:38 +0000193 from HTMLParser import HTMLParser
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
195 class MyHTMLParser(HTMLParser):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000196 def handle_starttag(self, tag, attrs):
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300197 print "Encountered a start tag:", tag
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198 def handle_endtag(self, tag):
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300199 print "Encountered an end tag:", tag
200 def handle_data(self, data):
201 print "Encountered some data:", data
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300203
204 parser = MyHTMLParser()
205 parser.feed('<html><head><title>Test</title></head>'
206 '<body><h1>Parse me!</h1></body></html>')