elementsoup.txt 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. ====================
  2. BeautifulSoup Parser
  3. ====================
  4. BeautifulSoup_ is a Python package that parses broken HTML, just like
  5. lxml supports it based on the parser of libxml2. BeautifulSoup uses a
  6. different parsing approach. It is not a real HTML parser but uses
  7. regular expressions to dive through tag soup. It is therefore more
  8. forgiving in some cases and less good in others. It is not uncommon
  9. that lxml/libxml2 parses and fixes broken HTML better, but
  10. BeautifulSoup has superiour `support for encoding detection`_. It
  11. very much depends on the input which parser works better.
  12. .. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/
  13. .. _`support for encoding detection`: http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode%2C%20Dammit
  14. .. _ElementSoup: http://effbot.org/zone/element-soup.htm
  15. To prevent users from having to choose their parser library in
  16. advance, lxml can interface to the parsing capabilities of
  17. BeautifulSoup through the ``lxml.html.soupparser`` module. It
  18. provides three main functions: ``fromstring()`` and ``parse()`` to
  19. parse a string or file using BeautifulSoup into an ``lxml.html``
  20. document, and ``convert_tree()`` to convert an existing BeautifulSoup
  21. tree into a list of top-level Elements.
  22. Parsing with the soupparser
  23. ===========================
  24. The functions ``fromstring()`` and ``parse()`` behave as known from
  25. ElementTree. The first returns a root Element, the latter returns an
  26. ElementTree.
  27. There is also a legacy module called ``lxml.html.ElementSoup``, which
  28. mimics the interface provided by ElementTree's own ElementSoup_
  29. module. Note that the ``soupparser`` module was added in lxml 2.0.3.
  30. Previous versions of lxml 2.0.x only have the ``ElementSoup`` module.
  31. Here is a document full of tag soup, similar to, but not quite like, HTML:
  32. .. sourcecode:: pycon
  33. >>> tag_soup = '<meta><head><title>Hello</head<body onload=crash()>Hi all<p>'
  34. all you need to do is pass it to the ``fromstring()`` function:
  35. .. sourcecode:: pycon
  36. >>> from lxml.html.soupparser import fromstring
  37. >>> root = fromstring(tag_soup)
  38. To see what we have here, you can serialise it:
  39. .. sourcecode:: pycon
  40. >>> from lxml.etree import tostring
  41. >>> print tostring(root, pretty_print=True),
  42. <html>
  43. <meta/>
  44. <head>
  45. <title>Hello</title>
  46. </head>
  47. <body onload="crash()">Hi all<p/></body>
  48. </html>
  49. Not quite what you'd expect from an HTML page, but, well, it was broken
  50. already, right? BeautifulSoup did its best, and so now it's a tree.
  51. To control which Element implementation is used, you can pass a
  52. ``makeelement`` factory function to ``parse()`` and ``fromstring()``.
  53. By default, this is based on the HTML parser defined in ``lxml.html``.
  54. Entity handling
  55. ===============
  56. By default, the BeautifulSoup parser also replaces the entities it
  57. finds by their character equivalent.
  58. .. sourcecode:: pycon
  59. >>> tag_soup = '<body>&copy;&euro;&#45;&#245;&#445;<p>'
  60. >>> body = fromstring(tag_soup).find('.//body')
  61. >>> body.text
  62. u'\xa9\u20ac-\xf5\u01bd'
  63. If you want them back on the way out, you can just serialise with the
  64. default encoding, which is 'US-ASCII'.
  65. .. sourcecode:: pycon
  66. >>> tostring(body)
  67. '<body>&#169;&#8364;-&#245;&#445;<p/></body>'
  68. >>> tostring(body, method="html")
  69. '<body>&#169;&#8364;-&#245;&#445;<p></p></body>'
  70. Any other encoding will output the respective byte sequences.
  71. .. sourcecode:: pycon
  72. >>> tostring(body, encoding="utf-8")
  73. '<body>\xc2\xa9\xe2\x82\xac-\xc3\xb5\xc6\xbd<p/></body>'
  74. >>> tostring(body, method="html", encoding="utf-8")
  75. '<body>\xc2\xa9\xe2\x82\xac-\xc3\xb5\xc6\xbd<p></p></body>'
  76. >>> tostring(body, encoding=unicode)
  77. u'<body>\xa9\u20ac-\xf5\u01bd<p/></body>'
  78. >>> tostring(body, method="html", encoding=unicode)
  79. u'<body>\xa9\u20ac-\xf5\u01bd<p></p></body>'
  80. Using soupparser as a fallback
  81. ==============================
  82. The downside of using this parser is that it is `much slower`_ than
  83. the HTML parser of lxml. So if performance matters, you might want to
  84. consider using ``soupparser`` only as a fallback for certain cases.
  85. .. _`much slower`: http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/
  86. One common problem of lxml's parser is that it might not get the
  87. encoding right in cases where the document contains a ``<meta>`` tag
  88. at the wrong place. In this case, you can exploit the fact that lxml
  89. serialises much faster than most other HTML libraries for Python.
  90. Just serialise the document to unicode and if that gives you an
  91. exception, re-parse it with BeautifulSoup to see if that works
  92. better.
  93. .. sourcecode:: pycon
  94. >>> tag_soup = '''\
  95. ... <meta http-equiv="Content-Type"
  96. ... content="text/html;charset=utf-8" />
  97. ... <html>
  98. ... <head>
  99. ... <title>Hello W\xc3\xb6rld!</title>
  100. ... </head>
  101. ... <body>Hi all</body>
  102. ... </html>'''
  103. >>> import lxml.html
  104. >>> import lxml.html.soupparser
  105. >>> root = lxml.html.fromstring(tag_soup)
  106. >>> try:
  107. ... ignore = tostring(root, encoding=unicode)
  108. ... except UnicodeDecodeError:
  109. ... root = lxml.html.soupparser.fromstring(tag_soup)