blob: e415700b3924d3c5416020c67a65516b0b54847c [file] [log] [blame]
Fred Drake3c50ea42008-05-17 22:02:32 +00001:mod:`html.parser` --- Simple HTML and XHTML parser
2===================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Fred Drake3c50ea42008-05-17 22:02:32 +00004.. module:: html.parser
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: A simple parser that can handle HTML and XHTML.
6
7
Georg Brandl9087b7f2008-05-18 07:53:01 +00008.. index::
9 single: HTML
10 single: XHTML
Georg Brandl116aa622007-08-15 14:28:22 +000011
12This module defines a class :class:`HTMLParser` which serves as the basis for
13parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
Georg Brandl116aa622007-08-15 14:28:22 +000014
R. David Murrayb579dba2010-12-03 04:06:39 +000015.. class:: HTMLParser(strict=True)
Georg Brandl116aa622007-08-15 14:28:22 +000016
R. David Murrayb579dba2010-12-03 04:06:39 +000017 Create a parser instance. If *strict* is ``True`` (the default), invalid
18 html results in :exc:`~html.parser.HTMLParseError` exceptions [#]_. If
19 *strict* is ``False``, the parser uses heuristics to make a best guess at
20 the intention of any invalid html it encounters, similar to the way most
21 browsers do.
Georg Brandl116aa622007-08-15 14:28:22 +000022
Fred Drake3c50ea42008-05-17 22:02:32 +000023 An :class:`HTMLParser` instance is fed HTML data and calls handler functions when tags
Georg Brandl116aa622007-08-15 14:28:22 +000024 begin and end. The :class:`HTMLParser` class is meant to be overridden by the
25 user to provide a desired behavior.
26
Georg Brandl877b10a2008-06-01 21:25:55 +000027 This parser does not check that end tags match start tags or call the end-tag
28 handler for elements which are closed implicitly by closing an outer element.
Georg Brandl116aa622007-08-15 14:28:22 +000029
R. David Murraybb7b7532010-12-03 04:26:18 +000030 .. versionchanged:: 3.2 *strict* keyword added
31
Georg Brandl116aa622007-08-15 14:28:22 +000032An exception is defined as well:
33
34
35.. exception:: HTMLParseError
36
37 Exception raised by the :class:`HTMLParser` class when it encounters an error
38 while parsing. This exception provides three attributes: :attr:`msg` is a brief
39 message explaining the error, :attr:`lineno` is the number of the line on which
40 the broken construct was detected, and :attr:`offset` is the number of
41 characters into the line at which the construct starts.
42
43:class:`HTMLParser` instances have the following methods:
44
45
46.. method:: HTMLParser.reset()
47
48 Reset the instance. Loses all unprocessed data. This is called implicitly at
49 instantiation time.
50
51
52.. method:: HTMLParser.feed(data)
53
54 Feed some text to the parser. It is processed insofar as it consists of
55 complete elements; incomplete data is buffered until more data is fed or
56 :meth:`close` is called.
57
58
59.. method:: HTMLParser.close()
60
61 Force processing of all buffered data as if it were followed by an end-of-file
62 mark. This method may be redefined by a derived class to define additional
63 processing at the end of the input, but the redefined version should always call
64 the :class:`HTMLParser` base class method :meth:`close`.
65
66
67.. method:: HTMLParser.getpos()
68
69 Return current line number and offset.
70
71
72.. method:: HTMLParser.get_starttag_text()
73
74 Return the text of the most recently opened start tag. This should not normally
75 be needed for structured processing, but may be useful in dealing with HTML "as
76 deployed" or for re-generating input with minimal changes (whitespace between
77 attributes can be preserved, etc.).
78
79
80.. method:: HTMLParser.handle_starttag(tag, attrs)
81
82 This method is called to handle the start of a tag. It is intended to be
83 overridden by a derived class; the base class implementation does nothing.
84
85 The *tag* argument is the name of the tag converted to lower case. The *attrs*
86 argument is a list of ``(name, value)`` pairs containing the attributes found
87 inside the tag's ``<>`` brackets. The *name* will be translated to lower case,
88 and quotes in the *value* have been removed, and character and entity references
89 have been replaced. For instance, for the tag ``<A
90 HREF="http://www.cwi.nl/">``, this method would be called as
91 ``handle_starttag('a', [('href', 'http://www.cwi.nl/')])``.
92
Georg Brandl9087b7f2008-05-18 07:53:01 +000093 All entity references from :mod:`html.entities` are replaced in the attribute
94 values.
Georg Brandl116aa622007-08-15 14:28:22 +000095
96
97.. method:: HTMLParser.handle_startendtag(tag, attrs)
98
99 Similar to :meth:`handle_starttag`, but called when the parser encounters an
100 XHTML-style empty tag (``<a .../>``). This method may be overridden by
101 subclasses which require this particular lexical information; the default
102 implementation simple calls :meth:`handle_starttag` and :meth:`handle_endtag`.
103
104
105.. method:: HTMLParser.handle_endtag(tag)
106
107 This method is called to handle the end tag of an element. It is intended to be
108 overridden by a derived class; the base class implementation does nothing. The
109 *tag* argument is the name of the tag converted to lower case.
110
111
112.. method:: HTMLParser.handle_data(data)
113
114 This method is called to process arbitrary data. It is intended to be
115 overridden by a derived class; the base class implementation does nothing.
116
117
118.. method:: HTMLParser.handle_charref(name)
119
120 This method is called to process a character reference of the form ``&#ref;``.
121 It is intended to be overridden by a derived class; the base class
122 implementation does nothing.
123
124
125.. method:: HTMLParser.handle_entityref(name)
126
127 This method is called to process a general entity reference of the form
128 ``&name;`` where *name* is an general entity reference. It is intended to be
129 overridden by a derived class; the base class implementation does nothing.
130
131
132.. method:: HTMLParser.handle_comment(data)
133
134 This method is called when a comment is encountered. The *comment* argument is
135 a string containing the text between the ``--`` and ``--`` delimiters, but not
136 the delimiters themselves. For example, the comment ``<!--text-->`` will cause
137 this method to be called with the argument ``'text'``. It is intended to be
138 overridden by a derived class; the base class implementation does nothing.
139
140
141.. method:: HTMLParser.handle_decl(decl)
142
Georg Brandl46aa5c52010-07-29 13:38:37 +0000143 Method called when an SGML ``doctype`` declaration is read by the parser.
144 The *decl* parameter will be the entire contents of the declaration inside
145 the ``<!...>`` markup. It is intended to be overridden by a derived class;
146 the base class implementation does nothing.
147
148
149.. method:: HTMLParser.unknown_decl(data)
150
151 Method called when an unrecognized SGML declaration is read by the parser.
152 The *data* parameter will be the entire contents of the declaration inside
153 the ``<!...>`` markup. It is sometimes useful to be be overridden by a
Georg Brandl7cb13192010-08-03 12:06:29 +0000154 derived class; the base class implementation raises an :exc:`HTMLParseError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156
157.. method:: HTMLParser.handle_pi(data)
158
159 Method called when a processing instruction is encountered. The *data*
160 parameter will contain the entire processing instruction. For example, for the
161 processing instruction ``<?proc color='red'>``, this method would be called as
162 ``handle_pi("proc color='red'")``. It is intended to be overridden by a derived
163 class; the base class implementation does nothing.
164
165 .. note::
166
167 The :class:`HTMLParser` class uses the SGML syntactic rules for processing
168 instructions. An XHTML processing instruction using the trailing ``'?'`` will
169 cause the ``'?'`` to be included in *data*.
170
171
172.. _htmlparser-example:
173
174Example HTML Parser Application
175-------------------------------
176
177As a basic example, below is a very basic HTML parser that uses the
178:class:`HTMLParser` class to print out tags as they are encountered::
179
Ezio Melotti2fad00c2009-06-27 22:58:15 +0000180 >>> from html.parser import HTMLParser
181 >>>
182 >>> class MyHTMLParser(HTMLParser):
183 ... def handle_starttag(self, tag, attrs):
184 ... print("Encountered a {} start tag".format(tag))
185 ... def handle_endtag(self, tag):
186 ... print("Encountered a {} end tag".format(tag))
187 ...
188 >>> page = """<html><h1>Title</h1><p>I'm a paragraph!</p></html>"""
189 >>>
190 >>> myparser = MyHTMLParser()
191 >>> myparser.feed(page)
192 Encountered a html start tag
193 Encountered a h1 start tag
194 Encountered a h1 end tag
195 Encountered a p start tag
196 Encountered a p end tag
197 Encountered a html end tag
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Georg Brandl116aa622007-08-15 14:28:22 +0000199
R. David Murrayb579dba2010-12-03 04:06:39 +0000200.. rubric:: Footnotes
201
R. David Murraybb7b7532010-12-03 04:26:18 +0000202.. [#] For backward compatibility reasons *strict* mode does not raise
203 exceptions for all non-compliant HTML. That is, some invalid HTML
R. David Murrayb579dba2010-12-03 04:06:39 +0000204 is tolerated even in *strict* mode.