Debian Codegraph @

doc/lxmlhtml.txt

raw
1 =========
2 lxml.html
3 =========
4
5 :Author:
6 Ian Bicking
7
8 Since version 2.0, lxml comes with a dedicated Python package for
9 dealing with HTML: ``lxml.html``. It is based on lxml's HTML parser,
10 but provides a special Element API for HTML elements, as well as a
11 number of utilities for common HTML processing tasks.
12
13 .. contents::
14 ..
15 1 Parsing HTML
16 1.1 Parsing HTML fragments
17 1.2 Really broken pages
18 2 HTML Element Methods
19 3 Running HTML doctests
20 4 Creating HTML with the E-factory
21 4.1 Viewing your HTML
22 5 Working with links
23 5.1 Functions
24 6 Forms
25 6.1 Form Filling Example
26 6.2 Form Submission
27 7 Cleaning up HTML
28 7.1 autolink
29 7.2 wordwrap
30 8 HTML Diff
31 9 Examples
32 9.1 Microformat Example
33
34 The main API is based on the `lxml.etree`_ API, and thus, on the ElementTree_
35 API.
36
37 .. _`lxml.etree`: tutorial.html
38 .. _ElementTree: http://effbot.org/zone/element-index.htm
39
40
41 Parsing HTML
42 ============
43
44 Parsing HTML fragments
45 ----------------------
46
47 There are several functions available to parse HTML:
48
49 ``parse(filename_url_or_file)``:
50 Parses the named file or url, or if the object has a ``.read()``
51 method, parses from that.
52
53 If you give a URL, or if the object has a ``.geturl()`` method (as
54 file-like objects from ``urllib.urlopen()`` have), then that URL
55 is used as the base URL. You can also provide an explicit
56 ``base_url`` keyword argument.
57
58 ``document_fromstring(string)``:
59 Parses a document from the given string. This always creates a
60 correct HTML document, which means the parent node is ``<html>``,
61 and there is a body and possibly a head.
62
63 ``fragment_fromstring(string, create_parent=False)``:
64 Returns an HTML fragment from a string. The fragment must contain
65 just a single element, unless ``create_parent`` is given;
66 e.g., ``fragment_fromstring(string, create_parent='div')`` will
67 wrap the element in a ``<div>``.
68
69 ``fragments_fromstring(string)``:
70 Returns a list of the elements found in the fragment.
71
72 ``fromstring(string)``:
73 Returns ``document_fromstring`` or ``fragment_fromstring``, based
74 on whether the string looks like a full document, or just a
75 fragment.
76
77 Really broken pages
78 -------------------
79
80 The normal HTML parser is capable of handling broken HTML, but for
81 pages that are far enough from HTML to call them 'tag soup', it may
82 still fail to parse the page in a useful way. A way to deal with this
83 is ElementSoup_, which deploys the well-known BeautifulSoup_ parser to
84 build an lxml HTML tree.
85
86 .. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/
87 .. _ElementSoup: elementsoup.html
88
89 However, note that the most common problem with web pages is the lack
90 of (or the existence of incorrect) encoding declarations. It is
91 therefore often sufficient to only use the encoding detection of
92 BeautifulSoup, called UnicodeDammit, and to leave the rest to lxml's
93 own HTML parser, which is several times faster.
94
95
96 HTML Element Methods
97 ====================
98
99 HTML elements have all the methods that come with ElementTree, but
100 also include some extra methods:
101
102 ``.drop_tree()``:
103 Drops the element and all its children. Unlike
104 ``el.getparent().remove(el)`` this does *not* remove the tail
105 text; with ``drop_tree`` the tail text is merged with the previous
106 element.
107
108 ``.drop_tag()``:
109 Drops the tag, but keeps its children and text.
110
111 ``.find_class(class_name)``:
112 Returns a list of all the elements with the given CSS class name.
113 Note that class names are space separated in HTML, so
114 ``doc.find_class('highlight')`` will find an element like
115 ``<div class="sidebar highlight">``. Class names *are* case
116 sensitive.
117
118 ``.find_rel_links(rel)``:
119 Returns a list of all the ``<a rel="{rel}">`` elements. E.g.,
120 ``doc.find_rel_links('tag')`` returns all the links `marked as
121 tags <http://microformats.org/wiki/rel-tag>`_.
122
123 ``.get_element_by_id(id, default=None)``:
124 Return the element with the given ``id``, or the ``default`` if
125 none is found. If there are multiple elements with the same id
126 (which there shouldn't be, but there often is), this returns only
127 the first.
128
129 ``.text_content()``:
130 Returns the text content of the element, including the text
131 content of its children, with no markup.
132
133 ``.cssselect(expr)``:
134 Select elements from this element and its children, using a CSS
135 selector expression. (Note that ``.xpath(expr)`` is also
136 available as on all lxml elements.)
137
138 ``.label``:
139 Returns the corresponding ``<label>`` element for this element, if
140 any exists (None if there is none). Label elements have a
141 ``label.for_element`` attribute that points back to the element.
142
143 ``.base_url``:
144 The base URL for this element, if one was saved from the parsing.
145 This attribute is not settable. Is None when no base URL was
146 saved.
147
148 ``.classes``:
149 Returns a set-like object that allows accessing and modifying the
150 names in the 'class' attribute of the element. (New in lxml 3.5).
151
152 ``.set(key, value=None)``:
153 Sets an HTML attribute. If no value is given, or if the value is
154 ``None``, it creates a boolean attribute like ``<form novalidate></form>``
155 or ``<div custom-attribute></div>``. In XML, attributes must
156 have at least the empty string as their value like ``<form
157 novalidate=""></form>``, but HTML boolean attributes can also be
158 just present or absent from an element without having a value.
159
160 Running HTML doctests
161 =====================
162
163 One of the interesting modules in the ``lxml.html`` package deals with
164 doctests. It can be hard to compare two HTML pages for equality, as
165 whitespace differences aren't meaningful and the structural formatting
166 can differ. This is even more of a problem in doctests, where output is
167 tested for equality and small differences in whitespace or the order
168 of attributes can let a test fail. And given the verbosity of
169 tag-based languages, it may take more than a quick look to find the
170 actual differences in the doctest output.
171
172 Luckily, lxml provides the ``lxml.doctestcompare`` module that
173 supports relaxed comparison of XML and HTML pages and provides a
174 readable diff in the output when a test fails. The HTML comparison is
175 most easily used by importing the ``usedoctest`` module in a doctest:
176
177 .. sourcecode:: pycon
178
179 >>> import lxml.html.usedoctest
180
181 Now, if you have an HTML document and want to compare it to an expected result
182 document in a doctest, you can do the following:
183
184 .. sourcecode:: pycon
185
186 >>> import lxml.html
187 >>> html = lxml.html.fromstring('''\
188 ... <html><body onload="" color="white">
189 ... <p>Hi !</p>
190 ... </body></html>
191 ... ''')
192
193 >>> print(lxml.html.tostring(html))
194 <html><body onload="" color="white"><p>Hi !</p></body></html>
195
196 >>> print(lxml.html.tostring(html))
197 <html> <body color="white" onload=""> <p>Hi !</p> </body> </html>
198
199 >>> print(lxml.html.tostring(html))
200 <html>
201 <body color="white" onload="">
202 <p>Hi !</p>
203 </body>
204 </html>
205
206 In documentation, you would likely prefer the pretty printed HTML output, as
207 it is the most readable. However, the three documents are equivalent from the
208 point of view of an HTML tool, so the doctest will silently accept any of the
209 above. This allows you to concentrate on readability in your doctests, even
210 if the real output is a straight ugly HTML one-liner.
211
212 Note that there is also an ``lxml.usedoctest`` module which you can
213 import for XML comparisons. The HTML parser notably ignores
214 namespaces and some other XMLisms.
215
216
217 Creating HTML with the E-factory
218 ================================
219
220 .. _`E-factory`: http://online.effbot.org/2006_11_01_archive.htm#et-builder
221
222 lxml.html comes with a predefined HTML vocabulary for the `E-factory`_,
223 originally written by Fredrik Lundh. This allows you to quickly generate HTML
224 pages and fragments:
225
226 .. sourcecode:: pycon
227
228 >>> from lxml.html import builder as E
229 >>> from lxml.html import usedoctest
230 >>> html = E.HTML(
231 ... E.HEAD(
232 ... E.LINK(rel="stylesheet", href="great.css", type="text/css"),
233 ... E.TITLE("Best Page Ever")
234 ... ),
235 ... E.BODY(
236 ... E.H1(E.CLASS("heading"), "Top News"),
237 ... E.P("World News only on this page", style="font-size: 200%"),
238 ... "Ah, and here's some more text, by the way.",
239 ... lxml.html.fromstring("<p>... and this is a parsed fragment ...</p>")
240 ... )
241 ... )
242
243 >>> print(lxml.html.tostring(html))
244 <html>
245 <head>
246 <link href="great.css" rel="stylesheet" type="text/css">
247 <title>Best Page Ever</title>
248 </head>
249 <body>
250 <h1 class="heading">Top News</h1>
251 <p style="font-size: 200%">World News only on this page</p>
252 Ah, and here's some more text, by the way.
253 <p>... and this is a parsed fragment ...</p>
254 </body>
255 </html>
256
257 Note that you should use ``lxml.html.tostring`` and **not**
258 ``lxml.tostring``. ``lxml.tostring(doc)`` will return the XML
259 representation of the document, which is not valid HTML. In
260 particular, things like ``<script src="..."></script>`` will be
261 serialized as ``<script src="..." />``, which completely confuses
262 browsers.
263
264 Viewing your HTML
265 -----------------
266
267 A handy method for viewing your HTML:
268 ``lxml.html.open_in_browser(lxml_doc)`` will write the document to
269 disk and open it in a browser (with the `webbrowser module
270 <http://python.org/doc/current/lib/module-webbrowser.html>`_).
271
272 Working with links
273 ==================
274
275 There are several methods on elements that allow you to see and modify
276 the links in a document.
277
278 ``.iterlinks()``:
279 This yields ``(element, attribute, link, pos)`` for every link in
280 the document. ``attribute`` may be None if the link is in the
281 text (as will be the case with a ``<style>`` tag with
282 ``@import``).
283
284 This finds any link in an ``action``, ``archive``, ``background``,
285 ``cite``, ``classid``, ``codebase``, ``data``, ``href``,
286 ``longdesc``, ``profile``, ``src``, ``usemap``, ``dynsrc``, or
287 ``lowsrc`` attribute. It also searches ``style`` attributes for
288 ``url(link)``, and ``<style>`` tags for ``@import`` and ``url()``.
289
290 This function does *not* pay attention to ``<base href>``.
291
292 ``.resolve_base_href()``:
293 This function will modify the document in-place to take account of
294 ``<base href>`` if the document contains that tag. In the process
295 it will also remove that tag from the document.
296
297 ``.make_links_absolute(base_href, resolve_base_href=True)``:
298 This makes all links in the document absolute, assuming that
299 ``base_href`` is the URL of the document. So if you pass
300 ``base_href="http://localhost/foo/bar.html"`` and there is a link
301 to ``baz.html`` that will be rewritten as
302 ``http://localhost/foo/baz.html``.
303
304 If ``resolve_base_href`` is true, then any ``<base href>`` tag
305 will be taken into account (just calling
306 ``self.resolve_base_href()``).
307
308 ``.rewrite_links(link_repl_func, resolve_base_href=True, base_href=None)``:
309 This rewrites all the links in the document using your given link
310 replacement function. If you give a ``base_href`` value, all
311 links will be passed in after they are joined with this URL.
312
313 For each link ``link_repl_func(link)`` is called. That function
314 then returns the new link, or None to remove the attribute or tag
315 that contains the link. Note that all links will be passed in,
316 including links like ``"#anchor"`` (which is purely internal), and
317 things like ``"mailto:[email protected]"`` (or ``javascript:...``).
318
319 If you want access to the context of the link, you should use
320 ``.iterlinks()`` instead.
321
322 Functions
323 ---------
324
325 In addition to these methods, there are corresponding functions:
326
327 * ``iterlinks(html)``
328 * ``make_links_absolute(html, base_href, ...)``
329 * ``rewrite_links(html, link_repl_func, ...)``
330 * ``resolve_base_href(html)``
331
332 These functions will parse ``html`` if it is a string, then return the new
333 HTML as a string. If you pass in a document, the document will be copied
334 (except for ``iterlinks()``), the method performed, and the new document
335 returned.
336
337 Forms
338 =====
339
340 Any ``<form>`` elements in a document are available through
341 the list ``doc.forms`` (e.g., ``doc.forms[0]``). Form, input, select,
342 and textarea elements each have special methods.
343
344 Input elements (including ``<select>`` and ``<textarea>``) have these
345 attributes:
346
347 ``.name``:
348 The name of the element.
349
350 ``.value``:
351 The value of an input, the content of a textarea, the selected
352 option(s) of a select. This attribute can be set.
353
354 In the case of a select that takes multiple options (``<select
355 multiple>``) this will be a set of the selected options; you can
356 add or remove items to select and unselect the options.
357
358 Select attributes:
359
360 ``.value_options``:
361 For select elements, this is all the *possible* values (the values
362 of all the options).
363
364 ``.multiple``:
365 For select elements, true if this is a ``<select multiple>``
366 element.
367
368 Input attributes:
369
370 ``.type``:
371 The type attribute in ``<input>`` elements.
372
373 ``.checkable``:
374 True if this can be checked (i.e., true for type=radio and
375 type=checkbox).
376
377 ``.checked``:
378 If this element is checkable, the checked state. Raises
379 AttributeError on non-checkable inputs.
380
381 The form itself has these attributes:
382
383 ``.inputs``:
384 A dictionary-like object that can be used to access input elements
385 by name. When there are multiple input elements with the same
386 name, this returns list-like structures that can also be used to
387 access the options and their values as a group.
388
389 ``.fields``:
390 A dictionary-like object used to access *values* by their name.
391 ``form.inputs`` returns elements, this only returns values.
392 Setting values in this dictionary will affect the form inputs.
393 Basically ``form.fields[x]`` is equivalent to
394 ``form.inputs[x].value`` and ``form.fields[x] = y`` is equivalent
395 to ``form.inputs[x].value = y``. (Note that sometimes
396 ``form.inputs[x]`` returns a compound object, but these objects
397 also have ``.value`` attributes.)
398
399 If you set this attribute, it is equivalent to
400 ``form.fields.clear(); form.fields.update(new_value)``
401
402 ``.form_values()``:
403 Returns a list of ``[(name, value), ...]``, suitable to be passed
404 to ``urllib.urlencode()`` for form submission.
405
406 ``.action``:
407 The ``action`` attribute. This is resolved to an absolute URL if
408 possible.
409
410 ``.method``:
411 The ``method`` attribute, which defaults to ``GET``.
412
413 Form Filling Example
414 --------------------
415
416 Note that you can change any of these attributes (values, method,
417 action, etc) and then serialize the form to see the updated values.
418 You can, for instance, do:
419
420 .. sourcecode:: pycon
421
422 >>> from lxml.html import fromstring, tostring
423 >>> form_page = fromstring('''<html><body><form>
424 ... Your name: <input type="text" name="name"> <br>
425 ... Your phone: <input type="text" name="phone"> <br>
426 ... Your favorite pets: <br>
427 ... Dogs: <input type="checkbox" name="interest" value="dogs"> <br>
428 ... Cats: <input type="checkbox" name="interest" value="cats"> <br>
429 ... Llamas: <input type="checkbox" name="interest" value="llamas"> <br>
430 ... <input type="submit"></form></body></html>''')
431 >>> form = form_page.forms[0]
432 >>> form.fields = dict(
433 ... name='John Smith',
434 ... phone='555-555-3949',
435 ... interest=set(['cats', 'llamas']))
436 >>> print(tostring(form))
437 <html>
438 <body>
439 <form>
440 Your name:
441 <input name="name" type="text" value="John Smith">
442 <br>Your phone:
443 <input name="phone" type="text" value="555-555-3949">
444 <br>Your favorite pets:
445 <br>Dogs:
446 <input name="interest" type="checkbox" value="dogs">
447 <br>Cats:
448 <input checked name="interest" type="checkbox" value="cats">
449 <br>Llamas:
450 <input checked name="interest" type="checkbox" value="llamas">
451 <br>
452 <input type="submit">
453 </form>
454 </body>
455 </html>
456
457
458 Form Submission
459 ---------------
460
461 You can submit a form with ``lxml.html.submit_form(form_element)``.
462 This will return a file-like object (the result of
463 ``urllib.urlopen()``).
464
465 If you have extra input values you want to pass you can use the
466 keyword argument ``extra_values``, like ``extra_values={'submit':
467 'Yes!'}``. This is the only way to get submit values into the form,
468 as there is no state of "submitted" for these elements.
469
470 You can pass in an alternate opener with the ``open_http`` keyword
471 argument, which is a function with the signature ``open_http(method,
472 url, values)``.
473
474 Example:
475
476 .. sourcecode:: pycon
477
478 >>> from lxml.html import parse, submit_form
479 >>> page = parse('http://tinyurl.com').getroot()
480 >>> page.forms[0].fields['url'] = 'http://lxml.de/'
481 >>> result = parse(submit_form(page.forms[0])).getroot()
482
483 >>> [a.attrib['href'] for a in result.xpath("//a[@target='_blank']")]
484 ['http://tinyurl.com/2xae8s', 'http://preview.tinyurl.com/2xae8s']
485
486
487 HTML Diff
488 =========
489
490 The module ``lxml.html.diff`` offers some ways to visualize
491 differences in HTML documents. These differences are *content*
492 oriented. That is, changes in markup are largely ignored; only
493 changes in the content itself are highlighted.
494
495 There are two ways to view differences: ``htmldiff`` and
496 ``html_annotate``. One shows differences with ``<ins>`` and
497 ``<del>``, while the other annotates a set of changes similar to ``svn
498 blame``. Both these functions operate on text, and work best with
499 content fragments (only what goes in ``<body>``), not complete
500 documents.
501
502 Example of ``htmldiff``:
503
504 .. sourcecode:: pycon
505
506 >>> from lxml.html.diff import htmldiff, html_annotate
507 >>> doc1 = '''<p>Here is some text.</p>'''
508 >>> doc2 = '''<p>Here is <b>a lot</b> of <i>text</i>.</p>'''
509 >>> doc3 = '''<p>Here is <b>a little</b> <i>text</i>.</p>'''
510 >>> print(htmldiff(doc1, doc2))
511 <p>Here is <ins><b>a lot</b> of <i>text</i>.</ins> <del>some text.</del> </p>
512 >>> print(html_annotate([(doc1, 'author1'), (doc2, 'author2'),
513 ... (doc3, 'author3')]))
514 <p><span title="author1">Here is</span>
515 <b><span title="author2">a</span>
516 <span title="author3">little</span></b>
517 <i><span title="author2">text</span></i>
518 <span title="author2">.</span></p>
519
520 As you can see, it is imperfect as such things tend to be. On larger
521 tracts of text with larger edits it will generally do better.
522
523 The ``html_annotate`` function can also take an optional second
524 argument, ``markup``. This is a function like ``markup(text,
525 version)`` that returns the given text marked up with the given
526 version. The default version, the output of which you see in the
527 example, looks like:
528
529 .. sourcecode:: python
530
531 def default_markup(text, version):
532 return '<span title="%s">%s</span>' % (
533 cgi.escape(unicode(version), 1), text)
534
535 Examples
536 ========
537
538 Microformat Example
539 -------------------
540
541 This example parses the `hCard <http://microformats.org/wiki/hcard>`_
542 microformat.
543
544 First we get the page:
545
546 .. sourcecode:: pycon
547
548 >>> import urllib
549 >>> from lxml.html import fromstring
550 >>> url = 'http://microformats.org/'
551 >>> content = urllib.urlopen(url).read()
552 >>> doc = fromstring(content)
553 >>> doc.make_links_absolute(url)
554
555 Then we create some objects to put the information in:
556
557 .. sourcecode:: pycon
558
559 >>> class Card(object):
560 ... def __init__(self, **kw):
561 ... for name, value in kw:
562 ... setattr(self, name, value)
563 >>> class Phone(object):
564 ... def __init__(self, phone, types=()):
565 ... self.phone, self.types = phone, types
566
567 And some generally handy functions for microformats:
568
569 .. sourcecode:: pycon
570
571 >>> def get_text(el, class_name):
572 ... els = el.find_class(class_name)
573 ... if els:
574 ... return els[0].text_content()
575 ... else:
576 ... return ''
577 >>> def get_value(el):
578 ... return get_text(el, 'value') or el.text_content()
579 >>> def get_all_texts(el, class_name):
580 ... return [e.text_content() for e in els.find_class(class_name)]
581 >>> def parse_addresses(el):
582 ... # Ideally this would parse street, etc.
583 ... return el.find_class('adr')
584
585 Then the parsing:
586
587 .. sourcecode:: pycon
588
589 >>> for el in doc.find_class('hcard'):
590 ... card = Card()
591 ... card.el = el
592 ... card.fn = get_text(el, 'fn')
593 ... card.tels = []
594 ... for tel_el in card.find_class('tel'):
595 ... card.tels.append(Phone(get_value(tel_el),
596 ... get_all_texts(tel_el, 'type')))
597 ... card.addresses = parse_addresses(el)