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