blob: adbcb38d9cdd50f4ce66cbd59f4e4f6800c8e86e [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
Ezio Melottid0ffcd62011-12-19 07:15:26 +020067 :meth:`close` is called. *data* can be either :class:`unicode` or
68 :class:`str`, but passing :class:`unicode` is advised.
Georg Brandl8ec7f652007-08-15 14:28:01 +000069
70
71.. method:: HTMLParser.close()
72
73 Force processing of all buffered data as if it were followed by an end-of-file
74 mark. This method may be redefined by a derived class to define additional
75 processing at the end of the input, but the redefined version should always call
76 the :class:`HTMLParser` base class method :meth:`close`.
77
78
79.. method:: HTMLParser.getpos()
80
81 Return current line number and offset.
82
83
84.. method:: HTMLParser.get_starttag_text()
85
86 Return the text of the most recently opened start tag. This should not normally
87 be needed for structured processing, but may be useful in dealing with HTML "as
88 deployed" or for re-generating input with minimal changes (whitespace between
89 attributes can be preserved, etc.).
90
91
92.. method:: HTMLParser.handle_starttag(tag, attrs)
93
94 This method is called to handle the start of a tag. It is intended to be
95 overridden by a derived class; the base class implementation does nothing.
96
97 The *tag* argument is the name of the tag converted to lower case. The *attrs*
98 argument is a list of ``(name, value)`` pairs containing the attributes found
99 inside the tag's ``<>`` brackets. The *name* will be translated to lower case,
100 and quotes in the *value* have been removed, and character and entity references
101 have been replaced. For instance, for the tag ``<A
102 HREF="http://www.cwi.nl/">``, this method would be called as
103 ``handle_starttag('a', [('href', 'http://www.cwi.nl/')])``.
104
105 .. versionchanged:: 2.6
Fred Draked995e112008-05-20 06:08:38 +0000106 All entity references from :mod:`htmlentitydefs` are now replaced in the attribute
107 values.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108
109
110.. method:: HTMLParser.handle_startendtag(tag, attrs)
111
112 Similar to :meth:`handle_starttag`, but called when the parser encounters an
Ezio Melotti87033522011-10-28 14:20:08 +0300113 XHTML-style empty tag (``<img ... />``). This method may be overridden by
Georg Brandl8ec7f652007-08-15 14:28:01 +0000114 subclasses which require this particular lexical information; the default
Ezio Melotti87033522011-10-28 14:20:08 +0300115 implementation simply calls :meth:`handle_starttag` and :meth:`handle_endtag`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000116
117
118.. method:: HTMLParser.handle_endtag(tag)
119
120 This method is called to handle the end tag of an element. It is intended to be
121 overridden by a derived class; the base class implementation does nothing. The
122 *tag* argument is the name of the tag converted to lower case.
123
124
125.. method:: HTMLParser.handle_data(data)
126
Ezio Melotti7e82b272011-11-01 14:09:56 +0200127 This method is called to process arbitrary data (e.g. the content of
128 ``<script>...</script>`` and ``<style>...</style>``). It is intended to be
Georg Brandl8ec7f652007-08-15 14:28:01 +0000129 overridden by a derived class; the base class implementation does nothing.
130
131
132.. method:: HTMLParser.handle_charref(name)
133
134 This method is called to process a character reference of the form ``&#ref;``.
135 It is intended to be overridden by a derived class; the base class
136 implementation does nothing.
137
138
139.. method:: HTMLParser.handle_entityref(name)
140
141 This method is called to process a general entity reference of the form
142 ``&name;`` where *name* is an general entity reference. It is intended to be
143 overridden by a derived class; the base class implementation does nothing.
144
145
146.. method:: HTMLParser.handle_comment(data)
147
148 This method is called when a comment is encountered. The *comment* argument is
149 a string containing the text between the ``--`` and ``--`` delimiters, but not
150 the delimiters themselves. For example, the comment ``<!--text-->`` will cause
151 this method to be called with the argument ``'text'``. It is intended to be
152 overridden by a derived class; the base class implementation does nothing.
153
154
155.. method:: HTMLParser.handle_decl(decl)
156
Georg Brandlc79d4322010-08-01 21:10:57 +0000157 Method called when an SGML ``doctype`` declaration is read by the parser.
158 The *decl* parameter will be the entire contents of the declaration inside
159 the ``<!...>`` markup. It is intended to be overridden by a derived class;
160 the base class implementation does nothing.
161
162
163.. method:: HTMLParser.unknown_decl(data)
164
165 Method called when an unrecognized SGML declaration is read by the parser.
166 The *data* parameter will be the entire contents of the declaration inside
Georg Brandlb6dc81d2011-03-21 08:55:16 +0100167 the ``<!...>`` markup. It is sometimes useful to be overridden by a
Georg Brandlc79d4322010-08-01 21:10:57 +0000168 derived class; the base class implementation throws an :exc:`HTMLParseError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169
170
171.. method:: HTMLParser.handle_pi(data)
172
173 Method called when a processing instruction is encountered. The *data*
174 parameter will contain the entire processing instruction. For example, for the
175 processing instruction ``<?proc color='red'>``, this method would be called as
176 ``handle_pi("proc color='red'")``. It is intended to be overridden by a derived
177 class; the base class implementation does nothing.
178
179 .. note::
180
181 The :class:`HTMLParser` class uses the SGML syntactic rules for processing
182 instructions. An XHTML processing instruction using the trailing ``'?'`` will
183 cause the ``'?'`` to be included in *data*.
184
185
186.. _htmlparser-example:
187
188Example HTML Parser Application
189-------------------------------
190
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300191As a basic example, below is a simple HTML parser that uses the
192:class:`HTMLParser` class to print out start tags, end tags and data
193as they are encountered::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
Fred Draked995e112008-05-20 06:08:38 +0000195 from HTMLParser import HTMLParser
Georg Brandl8ec7f652007-08-15 14:28:01 +0000196
197 class MyHTMLParser(HTMLParser):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198 def handle_starttag(self, tag, attrs):
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300199 print "Encountered a start tag:", tag
Georg Brandl8ec7f652007-08-15 14:28:01 +0000200 def handle_endtag(self, tag):
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300201 print "Encountered an end tag:", tag
202 def handle_data(self, data):
203 print "Encountered some data:", data
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204
Ezio Melottif9cc80d2011-10-28 14:14:34 +0300205
206 parser = MyHTMLParser()
207 parser.feed('<html><head><title>Test</title></head>'
208 '<body><h1>Parse me!</h1></body></html>')