| 1 |
==================== |
| 2 |
BeautifulSoup Parser |
| 3 |
==================== |
| 4 |
|
| 5 |
BeautifulSoup_ is a Python package for working with real-world and broken HTML, |
| 6 |
just like `lxml.html <lxmlhtml.html>`_. As of version 4.x, it can use |
| 7 |
`different HTML parsers |
| 8 |
<http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser>`_, |
| 9 |
each of which has its advantages and disadvantages (see the link). |
| 10 |
|
| 11 |
lxml can make use of BeautifulSoup as a parser backend, just like BeautifulSoup |
| 12 |
can employ lxml as a parser. When using BeautifulSoup from lxml, however, the |
| 13 |
default is to use Python's integrated HTML parser in the |
| 14 |
`html.parser <https://docs.python.org/3/library/html.parser.html>`_ module. |
| 15 |
In order to make use of the HTML5 parser of |
| 16 |
`html5lib <https://pypi.python.org/pypi/html5lib>`_ instead, it is better |
| 17 |
to go directly through the `html5parser module <html5parser.html>`_ in |
| 18 |
``lxml.html``. |
| 19 |
|
| 20 |
A very nice feature of BeautifulSoup is its excellent `support for encoding |
| 21 |
detection`_ which can provide better results for real-world HTML pages that |
| 22 |
do not (correctly) declare their encoding. |
| 23 |
|
| 24 |
.. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ |
| 25 |
.. _`support for encoding detection`: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#unicode-dammit |
| 26 |
.. _ElementSoup: http://effbot.org/zone/element-soup.htm |
| 27 |
|
| 28 |
lxml interfaces with BeautifulSoup through the ``lxml.html.soupparser`` |
| 29 |
module. It provides three main functions: ``fromstring()`` and ``parse()`` |
| 30 |
to parse a string or file using BeautifulSoup into an ``lxml.html`` |
| 31 |
document, and ``convert_tree()`` to convert an existing BeautifulSoup |
| 32 |
tree into a list of top-level Elements. |
| 33 |
|
| 34 |
.. contents:: |
| 35 |
.. |
| 36 |
1 Parsing with the soupparser |
| 37 |
2 Entity handling |
| 38 |
3 Using soupparser as a fallback |
| 39 |
4 Using only the encoding detection |
| 40 |
|
| 41 |
|
| 42 |
Parsing with the soupparser |
| 43 |
=========================== |
| 44 |
|
| 45 |
The functions ``fromstring()`` and ``parse()`` behave as known from |
| 46 |
lxml. The first returns a root Element, the latter returns an |
| 47 |
ElementTree. |
| 48 |
|
| 49 |
There is also a legacy module called ``lxml.html.ElementSoup``, which |
| 50 |
mimics the interface provided by Fredrik Lundh's ElementSoup_ |
| 51 |
module. Note that the ``soupparser`` module was added in lxml 2.0.3. |
| 52 |
Previous versions of lxml 2.0.x only have the ``ElementSoup`` module. |
| 53 |
|
| 54 |
Here is a document full of tag soup, similar to, but not quite like, HTML: |
| 55 |
|
| 56 |
.. sourcecode:: pycon |
| 57 |
|
| 58 |
>>> tag_soup = ''' |
| 59 |
... <meta/><head><title>Hello</head><body onload=crash()>Hi all<p>''' |
| 60 |
|
| 61 |
All you need to do is pass it to the ``fromstring()`` function: |
| 62 |
|
| 63 |
.. sourcecode:: pycon |
| 64 |
|
| 65 |
>>> from lxml.html.soupparser import fromstring |
| 66 |
>>> root = fromstring(tag_soup) |
| 67 |
|
| 68 |
To see what we have here, you can serialise it: |
| 69 |
|
| 70 |
.. sourcecode:: pycon |
| 71 |
|
| 72 |
>>> from lxml.etree import tostring |
| 73 |
>>> print(tostring(root, pretty_print=True).strip()) |
| 74 |
<html> |
| 75 |
<meta/> |
| 76 |
<head> |
| 77 |
<title>Hello</title> |
| 78 |
</head> |
| 79 |
<body onload="crash()">Hi all<p/></body> |
| 80 |
</html> |
| 81 |
|
| 82 |
Not quite what you'd expect from an HTML page, but, well, it was broken |
| 83 |
already, right? The parser did its best, and so now it's a tree. |
| 84 |
|
| 85 |
To control how Element objects are created during the conversion |
| 86 |
of the tree, you can pass a ``makeelement`` factory function to |
| 87 |
``parse()`` and ``fromstring()``. By default, this is based on the |
| 88 |
HTML parser defined in ``lxml.html``. |
| 89 |
|
| 90 |
For a quick comparison, libxml2 2.9.1 parses the same tag soup as |
| 91 |
follows. The only difference is that libxml2 tries harder to adhere |
| 92 |
to the structure of an HTML document and moves misplaced tags where |
| 93 |
they (likely) belong. Note, however, that the result can vary between |
| 94 |
parser versions. |
| 95 |
|
| 96 |
.. sourcecode:: html |
| 97 |
|
| 98 |
<html> |
| 99 |
<head> |
| 100 |
<meta/> |
| 101 |
<title>Hello</title> |
| 102 |
</head> |
| 103 |
<body onload="crash()">Hi all<p/></body> |
| 104 |
</html> |
| 105 |
|
| 106 |
|
| 107 |
Entity handling |
| 108 |
=============== |
| 109 |
|
| 110 |
By default, the BeautifulSoup parser also replaces the entities it |
| 111 |
finds by their character equivalent. |
| 112 |
|
| 113 |
.. sourcecode:: pycon |
| 114 |
|
| 115 |
>>> tag_soup = '<body>©€-õƽ<p>' |
| 116 |
>>> body = fromstring(tag_soup).find('.//body') |
| 117 |
>>> body.text |
| 118 |
'\xa9\u20ac-\xf5\u01bd' |
| 119 |
|
| 120 |
If you want them back on the way out, you can just serialise with the |
| 121 |
default encoding, which is 'US-ASCII'. |
| 122 |
|
| 123 |
.. sourcecode:: pycon |
| 124 |
|
| 125 |
>>> tostring(body) |
| 126 |
'<body>©€-õƽ<p/></body>' |
| 127 |
|
| 128 |
>>> tostring(body, method="html") |
| 129 |
'<body>©€-õƽ<p></p></body>' |
| 130 |
|
| 131 |
Any other encoding will output the respective byte sequences. |
| 132 |
|
| 133 |
.. sourcecode:: pycon |
| 134 |
|
| 135 |
>>> tostring(body, encoding="utf-8") |
| 136 |
'<body>\xc2\xa9\xe2\x82\xac-\xc3\xb5\xc6\xbd<p/></body>' |
| 137 |
|
| 138 |
>>> tostring(body, method="html", encoding="utf-8") |
| 139 |
'<body>\xc2\xa9\xe2\x82\xac-\xc3\xb5\xc6\xbd<p></p></body>' |
| 140 |
|
| 141 |
>>> tostring(body, encoding='unicode') |
| 142 |
'<body>\xa9\u20ac-\xf5\u01bd<p/></body>' |
| 143 |
|
| 144 |
>>> tostring(body, method="html", encoding='unicode') |
| 145 |
'<body>\xa9\u20ac-\xf5\u01bd<p></p></body>' |
| 146 |
|
| 147 |
|
| 148 |
Using soupparser as a fallback |
| 149 |
============================== |
| 150 |
|
| 151 |
The downside of using this parser is that it is `much slower`_ than |
| 152 |
the C implemented HTML parser of libxml2 that lxml uses. So if |
| 153 |
performance matters, you might want to consider using ``soupparser`` |
| 154 |
only as a fallback for certain cases. |
| 155 |
|
| 156 |
.. _`much slower`: http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ |
| 157 |
|
| 158 |
One common problem of lxml's parser is that it might not get the |
| 159 |
encoding right in cases where the document contains a ``<meta>`` tag |
| 160 |
at the wrong place. In this case, you can exploit the fact that lxml |
| 161 |
serialises much faster than most other HTML libraries for Python. |
| 162 |
Just serialise the document to unicode and if that gives you an |
| 163 |
exception, re-parse it with BeautifulSoup to see if that works |
| 164 |
better. |
| 165 |
|
| 166 |
.. sourcecode:: pycon |
| 167 |
|
| 168 |
>>> tag_soup = '''\ |
| 169 |
... <meta http-equiv="Content-Type" |
| 170 |
... content="text/html;charset=utf-8" /> |
| 171 |
... <html> |
| 172 |
... <head> |
| 173 |
... <title>Hello W\xc3\xb6rld!</title> |
| 174 |
... </head> |
| 175 |
... <body>Hi all</body> |
| 176 |
... </html>''' |
| 177 |
|
| 178 |
>>> import lxml.html |
| 179 |
>>> import lxml.html.soupparser |
| 180 |
|
| 181 |
>>> root = lxml.html.fromstring(tag_soup) |
| 182 |
>>> try: |
| 183 |
... ignore = tostring(root, encoding='unicode') |
| 184 |
... except UnicodeDecodeError: |
| 185 |
... root = lxml.html.soupparser.fromstring(tag_soup) |
| 186 |
|
| 187 |
|
| 188 |
Using only the encoding detection |
| 189 |
================================= |
| 190 |
|
| 191 |
Even if you prefer lxml's fast HTML parser, you can still benefit |
| 192 |
from BeautifulSoup's `support for encoding detection`_ in the |
| 193 |
``UnicodeDammit`` class. Once it succeeds in decoding the data, |
| 194 |
you can simply pass the resulting Unicode string into lxml's parser. |
| 195 |
|
| 196 |
.. sourcecode:: pycon |
| 197 |
|
| 198 |
>>> try: |
| 199 |
... from bs4 import UnicodeDammit # BeautifulSoup 4 |
| 200 |
... |
| 201 |
... def decode_html(html_string): |
| 202 |
... converted = UnicodeDammit(html_string) |
| 203 |
... if not converted.unicode_markup: |
| 204 |
... raise UnicodeDecodeError( |
| 205 |
... "Failed to detect encoding, tried [%s]", |
| 206 |
... ', '.join(converted.tried_encodings)) |
| 207 |
... # print converted.original_encoding |
| 208 |
... return converted.unicode_markup |
| 209 |
... |
| 210 |
... except ImportError: |
| 211 |
... from BeautifulSoup import UnicodeDammit # BeautifulSoup 3 |
| 212 |
... |
| 213 |
... def decode_html(html_string): |
| 214 |
... converted = UnicodeDammit(html_string, isHTML=True) |
| 215 |
... if not converted.unicode: |
| 216 |
... raise UnicodeDecodeError( |
| 217 |
... "Failed to detect encoding, tried [%s]", |
| 218 |
... ', '.join(converted.triedEncodings)) |
| 219 |
... # print converted.originalEncoding |
| 220 |
... return converted.unicode |
| 221 |
|
| 222 |
>>> root = lxml.html.fromstring(decode_html(tag_soup)) |