You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

343 lines
12 KiB

  1. :mod:`html.parser` --- Simple HTML and XHTML parser
  2. ===================================================
  3. .. module:: html.parser
  4. :synopsis: A simple parser that can handle HTML and XHTML.
  5. .. index::
  6. single: HTML
  7. single: XHTML
  8. **Source code:** :source:`Lib/html/parser.py`
  9. --------------
  10. This module defines a class :class:`HTMLParser` which serves as the basis for
  11. parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
  12. .. class:: HTMLParser(strict=True)
  13. Create a parser instance. If *strict* is ``True`` (the default), invalid
  14. HTML results in :exc:`~html.parser.HTMLParseError` exceptions [#]_. If
  15. *strict* is ``False``, the parser uses heuristics to make a best guess at
  16. the intention of any invalid HTML it encounters, similar to the way most
  17. browsers do. Using ``strict=False`` is advised.
  18. An :class:`.HTMLParser` instance is fed HTML data and calls handler methods
  19. when start tags, end tags, text, comments, and other markup elements are
  20. encountered. The user should subclass :class:`.HTMLParser` and override its
  21. methods to implement the desired behavior.
  22. This parser does not check that end tags match start tags or call the end-tag
  23. handler for elements which are closed implicitly by closing an outer element.
  24. .. versionchanged:: 3.2 *strict* keyword added
  25. An exception is defined as well:
  26. .. exception:: HTMLParseError
  27. Exception raised by the :class:`HTMLParser` class when it encounters an error
  28. while parsing and *strict* is ``True``. This exception provides three
  29. attributes: :attr:`msg` is a brief message explaining the error,
  30. :attr:`lineno` is the number of the line on which the broken construct was
  31. detected, and :attr:`offset` is the number of characters into the line at
  32. which the construct starts.
  33. Example HTML Parser Application
  34. -------------------------------
  35. As a basic example, below is a simple HTML parser that uses the
  36. :class:`HTMLParser` class to print out start tags, end tags, and data
  37. as they are encountered::
  38. from html.parser import HTMLParser
  39. class MyHTMLParser(HTMLParser):
  40. def handle_starttag(self, tag, attrs):
  41. print("Encountered a start tag:", tag)
  42. def handle_endtag(self, tag):
  43. print("Encountered an end tag :", tag)
  44. def handle_data(self, data):
  45. print("Encountered some data :", data)
  46. parser = MyHTMLParser(strict=False)
  47. parser.feed('<html><head><title>Test</title></head>'
  48. '<body><h1>Parse me!</h1></body></html>')
  49. The output will then be::
  50. Encountered a start tag: html
  51. Encountered a start tag: head
  52. Encountered a start tag: title
  53. Encountered some data : Test
  54. Encountered an end tag : title
  55. Encountered an end tag : head
  56. Encountered a start tag: body
  57. Encountered a start tag: h1
  58. Encountered some data : Parse me!
  59. Encountered an end tag : h1
  60. Encountered an end tag : body
  61. Encountered an end tag : html
  62. :class:`.HTMLParser` Methods
  63. ----------------------------
  64. :class:`HTMLParser` instances have the following methods:
  65. .. method:: HTMLParser.feed(data)
  66. Feed some text to the parser. It is processed insofar as it consists of
  67. complete elements; incomplete data is buffered until more data is fed or
  68. :meth:`close` is called. *data* must be :class:`str`.
  69. .. method:: HTMLParser.close()
  70. Force processing of all buffered data as if it were followed by an end-of-file
  71. mark. This method may be redefined by a derived class to define additional
  72. processing at the end of the input, but the redefined version should always call
  73. the :class:`HTMLParser` base class method :meth:`close`.
  74. .. method:: HTMLParser.reset()
  75. Reset the instance. Loses all unprocessed data. This is called implicitly at
  76. instantiation time.
  77. .. method:: HTMLParser.getpos()
  78. Return current line number and offset.
  79. .. method:: HTMLParser.get_starttag_text()
  80. Return the text of the most recently opened start tag. This should not normally
  81. be needed for structured processing, but may be useful in dealing with HTML "as
  82. deployed" or for re-generating input with minimal changes (whitespace between
  83. attributes can be preserved, etc.).
  84. The following methods are called when data or markup elements are encountered
  85. and they are meant to be overridden in a subclass. The base class
  86. implementations do nothing (except for :meth:`~HTMLParser.handle_startendtag`):
  87. .. method:: HTMLParser.handle_starttag(tag, attrs)
  88. This method is called to handle the start of a tag (e.g. ``<div id="main">``).
  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.
  94. For instance, for the tag ``<A HREF="http://www.cwi.nl/">``, this method
  95. would be called as ``handle_starttag('a', [('href', 'http://www.cwi.nl/')])``.
  96. All entity references from :mod:`html.entities` are replaced in the attribute
  97. values.
  98. .. method:: HTMLParser.handle_endtag(tag)
  99. This method is called to handle the end tag of an element (e.g. ``</div>``).
  100. The *tag* argument is the name of the tag converted to lower case.
  101. .. method:: HTMLParser.handle_startendtag(tag, attrs)
  102. Similar to :meth:`handle_starttag`, but called when the parser encounters an
  103. XHTML-style empty tag (``<img ... />``). This method may be overridden by
  104. subclasses which require this particular lexical information; the default
  105. implementation simply calls :meth:`handle_starttag` and :meth:`handle_endtag`.
  106. .. method:: HTMLParser.handle_data(data)
  107. This method is called to process arbitrary data (e.g. text nodes and the
  108. content of ``<script>...</script>`` and ``<style>...</style>``).
  109. .. method:: HTMLParser.handle_entityref(name)
  110. This method is called to process a named character reference of the form
  111. ``&name;`` (e.g. ``&gt;``), where *name* is a general entity reference
  112. (e.g. ``'gt'``).
  113. .. method:: HTMLParser.handle_charref(name)
  114. This method is called to process decimal and hexadecimal numeric character
  115. references of the form ``&#NNN;`` and ``&#xNNN;``. For example, the decimal
  116. equivalent for ``&gt;`` is ``&#62;``, whereas the hexadecimal is ``&#x3E;``;
  117. in this case the method will receive ``'62'`` or ``'x3E'``.
  118. .. method:: HTMLParser.handle_comment(data)
  119. This method is called when a comment is encountered (e.g. ``<!--comment-->``).
  120. For example, the comment ``<!-- comment -->`` will cause this method to be
  121. called with the argument ``' comment '``.
  122. The content of Internet Explorer conditional comments (condcoms) will also be
  123. sent to this method, so, for ``<!--[if IE 9]>IE9-specific content<![endif]-->``,
  124. this method will receive ``'[if IE 9]>IE-specific content<![endif]'``.
  125. .. method:: HTMLParser.handle_decl(decl)
  126. This method is called to handle an HTML doctype declaration (e.g.
  127. ``<!DOCTYPE html>``).
  128. The *decl* parameter will be the entire contents of the declaration inside
  129. the ``<!...>`` markup (e.g. ``'DOCTYPE html'``).
  130. .. method:: HTMLParser.handle_pi(data)
  131. Method called when a processing instruction is encountered. The *data*
  132. parameter will contain the entire processing instruction. For example, for the
  133. processing instruction ``<?proc color='red'>``, this method would be called as
  134. ``handle_pi("proc color='red'")``. It is intended to be overridden by a derived
  135. class; the base class implementation does nothing.
  136. .. note::
  137. The :class:`HTMLParser` class uses the SGML syntactic rules for processing
  138. instructions. An XHTML processing instruction using the trailing ``'?'`` will
  139. cause the ``'?'`` to be included in *data*.
  140. .. method:: HTMLParser.unknown_decl(data)
  141. This method is called when an unrecognized declaration is read by the parser.
  142. The *data* parameter will be the entire contents of the declaration inside
  143. the ``<![...]>`` markup. It is sometimes useful to be overridden by a
  144. derived class. The base class implementation raises an :exc:`HTMLParseError`
  145. when *strict* is ``True``.
  146. .. _htmlparser-examples:
  147. Examples
  148. --------
  149. The following class implements a parser that will be used to illustrate more
  150. examples::
  151. from html.parser import HTMLParser
  152. from html.entities import name2codepoint
  153. class MyHTMLParser(HTMLParser):
  154. def handle_starttag(self, tag, attrs):
  155. print("Start tag:", tag)
  156. for attr in attrs:
  157. print(" attr:", attr)
  158. def handle_endtag(self, tag):
  159. print("End tag :", tag)
  160. def handle_data(self, data):
  161. print("Data :", data)
  162. def handle_comment(self, data):
  163. print("Comment :", data)
  164. def handle_entityref(self, name):
  165. c = chr(name2codepoint[name])
  166. print("Named ent:", c)
  167. def handle_charref(self, name):
  168. if name.startswith('x'):
  169. c = chr(int(name[1:], 16))
  170. else:
  171. c = chr(int(name))
  172. print("Num ent :", c)
  173. def handle_decl(self, data):
  174. print("Decl :", data)
  175. parser = MyHTMLParser(strict=False)
  176. Parsing a doctype::
  177. >>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
  178. ... '"http://www.w3.org/TR/html4/strict.dtd">')
  179. Decl : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
  180. Parsing an element with a few attributes and a title::
  181. >>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
  182. Start tag: img
  183. attr: ('src', 'python-logo.png')
  184. attr: ('alt', 'The Python logo')
  185. >>>
  186. >>> parser.feed('<h1>Python</h1>')
  187. Start tag: h1
  188. Data : Python
  189. End tag : h1
  190. The content of ``script`` and ``style`` elements is returned as is, without
  191. further parsing::
  192. >>> parser.feed('<style type="text/css">#python { color: green }</style>')
  193. Start tag: style
  194. attr: ('type', 'text/css')
  195. Data : #python { color: green }
  196. End tag : style
  197. >>>
  198. >>> parser.feed('<script type="text/javascript">'
  199. ... 'alert("<strong>hello!</strong>");</script>')
  200. Start tag: script
  201. attr: ('type', 'text/javascript')
  202. Data : alert("<strong>hello!</strong>");
  203. End tag : script
  204. Parsing comments::
  205. >>> parser.feed('<!-- a comment -->'
  206. ... '<!--[if IE 9]>IE-specific content<![endif]-->')
  207. Comment : a comment
  208. Comment : [if IE 9]>IE-specific content<![endif]
  209. Parsing named and numeric character references and converting them to the
  210. correct char (note: these 3 references are all equivalent to ``'>'``)::
  211. >>> parser.feed('&gt;&#62;&#x3E;')
  212. Named ent: >
  213. Num ent : >
  214. Num ent : >
  215. Feeding incomplete chunks to :meth:`~HTMLParser.feed` works, but
  216. :meth:`~HTMLParser.handle_data` might be called more than once::
  217. >>> for chunk in ['<sp', 'an>buff', 'ered ', 'text</s', 'pan>']:
  218. ... parser.feed(chunk)
  219. ...
  220. Start tag: span
  221. Data : buff
  222. Data : ered
  223. Data : text
  224. End tag : span
  225. Parsing invalid HTML (e.g. unquoted attributes) also works::
  226. >>> parser.feed('<p><a class=link href=#main>tag soup</p ></a>')
  227. Start tag: p
  228. Start tag: a
  229. attr: ('class', 'link')
  230. attr: ('href', '#main')
  231. Data : tag soup
  232. End tag : p
  233. End tag : a
  234. .. rubric:: Footnotes
  235. .. [#] For backward compatibility reasons *strict* mode does not raise
  236. exceptions for all non-compliant HTML. That is, some invalid HTML
  237. is tolerated even in *strict* mode.