blob: aa10498042b66a52071acb1f5e5f25bbeeb7866e [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
Ezio Melotti87033522011-10-28 14:20:08 +030011 3. The :term:`2to3` tool will automatically adapt imports when converting
12 your sources to Python 3.
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
Ezio Melotti87033522011-10-28 14:20:08 +0300112 XHTML-style empty tag (``<img ... />``). This method may be overridden by
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113 subclasses which require this particular lexical information; the default
Ezio Melotti87033522011-10-28 14:20:08 +0300114 implementation simply calls :meth:`handle_starttag` and :meth:`handle_endtag`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000115
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
Ezio Melotti7e82b272011-11-01 14:09:56 +0200126 This method is called to process arbitrary data (e.g. the content of
127 ``<script>...</script>`` and ``<style>...</style>``). It is intended to be
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128 overridden by a derived class; the base class implementation does nothing.
129
130
131.. method:: HTMLParser.handle_charref(name)
132
133 This method is called to process a character reference of the form ``&#ref;``.
134 It is intended to be overridden by a derived class; the base class
135 implementation does nothing.
136
137
138.. method:: HTMLParser.handle_entityref(name)
139
140 This method is called to process a general entity reference of the form
141 ``&name;`` where *name* is an general entity reference. It is intended to be
142 overridden by a derived class; the base class implementation does nothing.
143
144
145.. method:: HTMLParser.handle_comment(data)
146
147 This method is called when a comment is encountered. The *comment* argument is
148 a string containing the text between the ``--`` and ``--`` delimiters, but not
149 the delimiters themselves. For example, the comment ``<!--text-->`` will cause
150 this method to be called with the argument ``'text'``. It is intended to be
151 overridden by a derived class; the base class implementation does nothing.
152
153
154.. method:: HTMLParser.handle_decl(decl)
155
Georg Brandlc79d4322010-08-01 21:10:57 +0000156 Method called when an SGML ``doctype`` declaration is read by the parser.
157 The *decl* parameter will be the entire contents of the declaration inside
158 the ``<!...>`` markup. It is intended to be overridden by a derived class;
159 the base class implementation does nothing.
160
161
162.. method:: HTMLParser.unknown_decl(data)
163
164 Method called when an unrecognized SGML declaration is read by the parser.
165 The *data* parameter will be the entire contents of the declaration inside
Georg Brandlb6dc81d2011-03-21 08:55:16 +0100166 the ``<!...>`` markup. It is sometimes useful to be overridden by a
Georg Brandlc79d4322010-08-01 21:10:57 +0000167 derived class; the base class implementation throws an :exc:`HTMLParseError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000168
169
170.. method:: HTMLParser.handle_pi(data)
171
172 Method called when a processing instruction is encountered. The *data*
173 parameter will contain the entire processing instruction. For example, for the
174 processing instruction ``<?proc color='red'>``, this method would be called as
175 ``handle_pi("proc color='red'")``. It is intended to be overridden by a derived
176 class; the base class implementation does nothing.
177
178 .. note::
179
180 The :class:`HTMLParser` class uses the SGML syntactic rules for processing
181 instructions. An XHTML processing instruction using the trailing ``'?'`` will
182 cause the ``'?'`` to be included in *data*.
183
184
185.. _htmlparser-example:
186
187Example HTML Parser Application
188-------------------------------
189
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300190As a basic example, below is a simple HTML parser that uses the
191:class:`HTMLParser` class to print out start tags, end tags and data
192as they are encountered::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
Fred Draked995e112008-05-20 06:08:38 +0000194 from HTMLParser import HTMLParser
Georg Brandl8ec7f652007-08-15 14:28:01 +0000195
196 class MyHTMLParser(HTMLParser):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000197 def handle_starttag(self, tag, attrs):
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300198 print "Encountered a start tag:", tag
Georg Brandl8ec7f652007-08-15 14:28:01 +0000199 def handle_endtag(self, tag):
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300200 print "Encountered an end tag:", tag
201 def handle_data(self, data):
202 print "Encountered some data:", data
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300204
205 parser = MyHTMLParser()
206 parser.feed('<html><head><title>Test</title></head>'
207 '<body><h1>Parse me!</h1></body></html>')