lxmlhtml.txt 25 KB

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