/Doc/library/htmlparser.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 189 lines · 116 code · 73 blank · 0 comment · 0 complexity · 7f9f08275cfced5712279ba53d221206 MD5 · raw file

  1. :mod:`HTMLParser` --- Simple HTML and XHTML parser
  2. ==================================================
  3. .. module:: HTMLParser
  4. :synopsis: A simple parser that can handle HTML and XHTML.
  5. .. note::
  6. The :mod:`HTMLParser` module has been renamed to :mod:`html.parser` in Python
  7. 3.0. The :term:`2to3` tool will automatically adapt imports when converting
  8. your sources to 3.0.
  9. .. versionadded:: 2.2
  10. .. index::
  11. single: HTML
  12. single: XHTML
  13. This module defines a class :class:`HTMLParser` which serves as the basis for
  14. parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
  15. Unlike the parser in :mod:`htmllib`, this parser is not based on the SGML parser
  16. in :mod:`sgmllib`.
  17. .. class:: HTMLParser()
  18. The :class:`HTMLParser` class is instantiated without arguments.
  19. An :class:`HTMLParser` instance is fed HTML data and calls handler functions when tags
  20. begin and end. The :class:`HTMLParser` class is meant to be overridden by the
  21. user to provide a desired behavior.
  22. Unlike the parser in :mod:`htmllib`, this parser does not check that end tags
  23. match start tags or call the end-tag handler for elements which are closed
  24. implicitly by closing an outer element.
  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. This exception provides three attributes: :attr:`msg` is a brief
  29. message explaining the error, :attr:`lineno` is the number of the line on which
  30. the broken construct was detected, and :attr:`offset` is the number of
  31. characters into the line at which the construct starts.
  32. :class:`HTMLParser` instances have the following methods:
  33. .. method:: HTMLParser.reset()
  34. Reset the instance. Loses all unprocessed data. This is called implicitly at
  35. instantiation time.
  36. .. method:: HTMLParser.feed(data)
  37. Feed some text to the parser. It is processed insofar as it consists of
  38. complete elements; incomplete data is buffered until more data is fed or
  39. :meth:`close` is called.
  40. .. method:: HTMLParser.close()
  41. Force processing of all buffered data as if it were followed by an end-of-file
  42. mark. This method may be redefined by a derived class to define additional
  43. processing at the end of the input, but the redefined version should always call
  44. the :class:`HTMLParser` base class method :meth:`close`.
  45. .. method:: HTMLParser.getpos()
  46. Return current line number and offset.
  47. .. method:: HTMLParser.get_starttag_text()
  48. Return the text of the most recently opened start tag. This should not normally
  49. be needed for structured processing, but may be useful in dealing with HTML "as
  50. deployed" or for re-generating input with minimal changes (whitespace between
  51. attributes can be preserved, etc.).
  52. .. method:: HTMLParser.handle_starttag(tag, attrs)
  53. This method is called to handle the start of a tag. It is intended to be
  54. overridden by a derived class; the base class implementation does nothing.
  55. The *tag* argument is the name of the tag converted to lower case. The *attrs*
  56. argument is a list of ``(name, value)`` pairs containing the attributes found
  57. inside the tag's ``<>`` brackets. The *name* will be translated to lower case,
  58. and quotes in the *value* have been removed, and character and entity references
  59. have been replaced. For instance, for the tag ``<A
  60. HREF="http://www.cwi.nl/">``, this method would be called as
  61. ``handle_starttag('a', [('href', 'http://www.cwi.nl/')])``.
  62. .. versionchanged:: 2.6
  63. All entity references from :mod:`htmlentitydefs` are now replaced in the attribute
  64. values.
  65. .. method:: HTMLParser.handle_startendtag(tag, attrs)
  66. Similar to :meth:`handle_starttag`, but called when the parser encounters an
  67. XHTML-style empty tag (``<a .../>``). This method may be overridden by
  68. subclasses which require this particular lexical information; the default
  69. implementation simple calls :meth:`handle_starttag` and :meth:`handle_endtag`.
  70. .. method:: HTMLParser.handle_endtag(tag)
  71. This method is called to handle the end tag of an element. It is intended to be
  72. overridden by a derived class; the base class implementation does nothing. The
  73. *tag* argument is the name of the tag converted to lower case.
  74. .. method:: HTMLParser.handle_data(data)
  75. This method is called to process arbitrary data. It is intended to be
  76. overridden by a derived class; the base class implementation does nothing.
  77. .. method:: HTMLParser.handle_charref(name)
  78. This method is called to process a character reference of the form ``&#ref;``.
  79. It is intended to be overridden by a derived class; the base class
  80. implementation does nothing.
  81. .. method:: HTMLParser.handle_entityref(name)
  82. This method is called to process a general entity reference of the form
  83. ``&name;`` where *name* is an general entity reference. It is intended to be
  84. overridden by a derived class; the base class implementation does nothing.
  85. .. method:: HTMLParser.handle_comment(data)
  86. This method is called when a comment is encountered. The *comment* argument is
  87. a string containing the text between the ``--`` and ``--`` delimiters, but not
  88. the delimiters themselves. For example, the comment ``<!--text-->`` will cause
  89. this method to be called with the argument ``'text'``. It is intended to be
  90. overridden by a derived class; the base class implementation does nothing.
  91. .. method:: HTMLParser.handle_decl(decl)
  92. Method called when an SGML declaration is read by the parser. The *decl*
  93. parameter will be the entire contents of the declaration inside the ``<!``...\
  94. ``>`` markup. It is intended to be overridden by a derived class; the base
  95. class implementation does nothing.
  96. .. method:: HTMLParser.handle_pi(data)
  97. Method called when a processing instruction is encountered. The *data*
  98. parameter will contain the entire processing instruction. For example, for the
  99. processing instruction ``<?proc color='red'>``, this method would be called as
  100. ``handle_pi("proc color='red'")``. It is intended to be overridden by a derived
  101. class; the base class implementation does nothing.
  102. .. note::
  103. The :class:`HTMLParser` class uses the SGML syntactic rules for processing
  104. instructions. An XHTML processing instruction using the trailing ``'?'`` will
  105. cause the ``'?'`` to be included in *data*.
  106. .. _htmlparser-example:
  107. Example HTML Parser Application
  108. -------------------------------
  109. As a basic example, below is a very basic HTML parser that uses the
  110. :class:`HTMLParser` class to print out tags as they are encountered::
  111. from HTMLParser import HTMLParser
  112. class MyHTMLParser(HTMLParser):
  113. def handle_starttag(self, tag, attrs):
  114. print "Encountered the beginning of a %s tag" % tag
  115. def handle_endtag(self, tag):
  116. print "Encountered the end of a %s tag" % tag