lxmlhtml.txt 25 KB

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