You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1927 lines
63 KiB

4 years ago
  1. # Copyright (c) 2004 Ian Bicking. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are
  5. # met:
  6. #
  7. # 1. Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. #
  10. # 2. Redistributions in binary form must reproduce the above copyright
  11. # notice, this list of conditions and the following disclaimer in
  12. # the documentation and/or other materials provided with the
  13. # distribution.
  14. #
  15. # 3. Neither the name of Ian Bicking nor the names of its contributors may
  16. # be used to endorse or promote products derived from this software
  17. # without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IAN BICKING OR
  23. # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24. # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25. # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26. # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27. # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28. # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """The ``lxml.html`` tool set for HTML handling.
  31. """
  32. from __future__ import absolute_import
  33. __all__ = [
  34. 'document_fromstring', 'fragment_fromstring', 'fragments_fromstring', 'fromstring',
  35. 'tostring', 'Element', 'defs', 'open_in_browser', 'submit_form',
  36. 'find_rel_links', 'find_class', 'make_links_absolute',
  37. 'resolve_base_href', 'iterlinks', 'rewrite_links', 'open_in_browser', 'parse']
  38. import copy
  39. import sys
  40. import re
  41. from functools import partial
  42. try:
  43. # while unnecessary, importing from 'collections.abc' is the right way to do it
  44. from collections.abc import MutableMapping, MutableSet
  45. except ImportError:
  46. from collections import MutableMapping, MutableSet
  47. from .. import etree
  48. from . import defs
  49. from ._setmixin import SetMixin
  50. try:
  51. from urlparse import urljoin
  52. except ImportError:
  53. # Python 3
  54. from urllib.parse import urljoin
  55. try:
  56. unicode
  57. except NameError:
  58. # Python 3
  59. unicode = str
  60. try:
  61. basestring
  62. except NameError:
  63. # Python 3
  64. basestring = (str, bytes)
  65. def __fix_docstring(s):
  66. if not s:
  67. return s
  68. if sys.version_info[0] >= 3:
  69. sub = re.compile(r"^(\s*)u'", re.M).sub
  70. else:
  71. sub = re.compile(r"^(\s*)b'", re.M).sub
  72. return sub(r"\1'", s)
  73. XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"
  74. _rel_links_xpath = etree.XPath("descendant-or-self::a[@rel]|descendant-or-self::x:a[@rel]",
  75. namespaces={'x':XHTML_NAMESPACE})
  76. _options_xpath = etree.XPath("descendant-or-self::option|descendant-or-self::x:option",
  77. namespaces={'x':XHTML_NAMESPACE})
  78. _forms_xpath = etree.XPath("descendant-or-self::form|descendant-or-self::x:form",
  79. namespaces={'x':XHTML_NAMESPACE})
  80. #_class_xpath = etree.XPath(r"descendant-or-self::*[regexp:match(@class, concat('\b', $class_name, '\b'))]", {'regexp': 'http://exslt.org/regular-expressions'})
  81. _class_xpath = etree.XPath("descendant-or-self::*[@class and contains(concat(' ', normalize-space(@class), ' '), concat(' ', $class_name, ' '))]")
  82. _id_xpath = etree.XPath("descendant-or-self::*[@id=$id]")
  83. _collect_string_content = etree.XPath("string()")
  84. _iter_css_urls = re.compile(r'url\(('+'["][^"]*["]|'+"['][^']*[']|"+r'[^)]*)\)', re.I).finditer
  85. _iter_css_imports = re.compile(r'@import "(.*?)"').finditer
  86. _label_xpath = etree.XPath("//label[@for=$id]|//x:label[@for=$id]",
  87. namespaces={'x':XHTML_NAMESPACE})
  88. _archive_re = re.compile(r'[^ ]+')
  89. _parse_meta_refresh_url = re.compile(
  90. r'[^;=]*;\s*(?:url\s*=\s*)?(?P<url>.*)$', re.I).search
  91. def _unquote_match(s, pos):
  92. if s[:1] == '"' and s[-1:] == '"' or s[:1] == "'" and s[-1:] == "'":
  93. return s[1:-1], pos+1
  94. else:
  95. return s,pos
  96. def _transform_result(typ, result):
  97. """Convert the result back into the input type.
  98. """
  99. if issubclass(typ, bytes):
  100. return tostring(result, encoding='utf-8')
  101. elif issubclass(typ, unicode):
  102. return tostring(result, encoding='unicode')
  103. else:
  104. return result
  105. def _nons(tag):
  106. if isinstance(tag, basestring):
  107. if tag[0] == '{' and tag[1:len(XHTML_NAMESPACE)+1] == XHTML_NAMESPACE:
  108. return tag.split('}')[-1]
  109. return tag
  110. class Classes(MutableSet):
  111. """Provides access to an element's class attribute as a set-like collection.
  112. Usage::
  113. >>> el = fromstring('<p class="hidden large">Text</p>')
  114. >>> classes = el.classes # or: classes = Classes(el.attrib)
  115. >>> classes |= ['block', 'paragraph']
  116. >>> el.get('class')
  117. 'hidden large block paragraph'
  118. >>> classes.toggle('hidden')
  119. False
  120. >>> el.get('class')
  121. 'large block paragraph'
  122. >>> classes -= ('some', 'classes', 'block')
  123. >>> el.get('class')
  124. 'large paragraph'
  125. """
  126. def __init__(self, attributes):
  127. self._attributes = attributes
  128. self._get_class_value = partial(attributes.get, 'class', '')
  129. def add(self, value):
  130. """
  131. Add a class.
  132. This has no effect if the class is already present.
  133. """
  134. if not value or re.search(r'\s', value):
  135. raise ValueError("Invalid class name: %r" % value)
  136. classes = self._get_class_value().split()
  137. if value in classes:
  138. return
  139. classes.append(value)
  140. self._attributes['class'] = ' '.join(classes)
  141. def discard(self, value):
  142. """
  143. Remove a class if it is currently present.
  144. If the class is not present, do nothing.
  145. """
  146. if not value or re.search(r'\s', value):
  147. raise ValueError("Invalid class name: %r" % value)
  148. classes = [name for name in self._get_class_value().split()
  149. if name != value]
  150. if classes:
  151. self._attributes['class'] = ' '.join(classes)
  152. elif 'class' in self._attributes:
  153. del self._attributes['class']
  154. def remove(self, value):
  155. """
  156. Remove a class; it must currently be present.
  157. If the class is not present, raise a KeyError.
  158. """
  159. if not value or re.search(r'\s', value):
  160. raise ValueError("Invalid class name: %r" % value)
  161. super(Classes, self).remove(value)
  162. def __contains__(self, name):
  163. classes = self._get_class_value()
  164. return name in classes and name in classes.split()
  165. def __iter__(self):
  166. return iter(self._get_class_value().split())
  167. def __len__(self):
  168. return len(self._get_class_value().split())
  169. # non-standard methods
  170. def update(self, values):
  171. """
  172. Add all names from 'values'.
  173. """
  174. classes = self._get_class_value().split()
  175. extended = False
  176. for value in values:
  177. if value not in classes:
  178. classes.append(value)
  179. extended = True
  180. if extended:
  181. self._attributes['class'] = ' '.join(classes)
  182. def toggle(self, value):
  183. """
  184. Add a class name if it isn't there yet, or remove it if it exists.
  185. Returns true if the class was added (and is now enabled) and
  186. false if it was removed (and is now disabled).
  187. """
  188. if not value or re.search(r'\s', value):
  189. raise ValueError("Invalid class name: %r" % value)
  190. classes = self._get_class_value().split()
  191. try:
  192. classes.remove(value)
  193. enabled = False
  194. except ValueError:
  195. classes.append(value)
  196. enabled = True
  197. if classes:
  198. self._attributes['class'] = ' '.join(classes)
  199. else:
  200. del self._attributes['class']
  201. return enabled
  202. class HtmlMixin(object):
  203. def set(self, key, value=None):
  204. """set(self, key, value=None)
  205. Sets an element attribute. If no value is provided, or if the value is None,
  206. creates a 'boolean' attribute without value, e.g. "<form novalidate></form>"
  207. for ``form.set('novalidate')``.
  208. """
  209. super(HtmlElement, self).set(key, value)
  210. @property
  211. def classes(self):
  212. """
  213. A set-like wrapper around the 'class' attribute.
  214. """
  215. return Classes(self.attrib)
  216. @classes.setter
  217. def classes(self, classes):
  218. assert isinstance(classes, Classes) # only allow "el.classes |= ..." etc.
  219. value = classes._get_class_value()
  220. if value:
  221. self.set('class', value)
  222. elif self.get('class') is not None:
  223. del self.attrib['class']
  224. @property
  225. def base_url(self):
  226. """
  227. Returns the base URL, given when the page was parsed.
  228. Use with ``urlparse.urljoin(el.base_url, href)`` to get
  229. absolute URLs.
  230. """
  231. return self.getroottree().docinfo.URL
  232. @property
  233. def forms(self):
  234. """
  235. Return a list of all the forms
  236. """
  237. return _forms_xpath(self)
  238. @property
  239. def body(self):
  240. """
  241. Return the <body> element. Can be called from a child element
  242. to get the document's head.
  243. """
  244. return self.xpath('//body|//x:body', namespaces={'x':XHTML_NAMESPACE})[0]
  245. @property
  246. def head(self):
  247. """
  248. Returns the <head> element. Can be called from a child
  249. element to get the document's head.
  250. """
  251. return self.xpath('//head|//x:head', namespaces={'x':XHTML_NAMESPACE})[0]
  252. @property
  253. def label(self):
  254. """
  255. Get or set any <label> element associated with this element.
  256. """
  257. id = self.get('id')
  258. if not id:
  259. return None
  260. result = _label_xpath(self, id=id)
  261. if not result:
  262. return None
  263. else:
  264. return result[0]
  265. @label.setter
  266. def label(self, label):
  267. id = self.get('id')
  268. if not id:
  269. raise TypeError(
  270. "You cannot set a label for an element (%r) that has no id"
  271. % self)
  272. if _nons(label.tag) != 'label':
  273. raise TypeError(
  274. "You can only assign label to a label element (not %r)"
  275. % label)
  276. label.set('for', id)
  277. @label.deleter
  278. def label(self):
  279. label = self.label
  280. if label is not None:
  281. del label.attrib['for']
  282. def drop_tree(self):
  283. """
  284. Removes this element from the tree, including its children and
  285. text. The tail text is joined to the previous element or
  286. parent.
  287. """
  288. parent = self.getparent()
  289. assert parent is not None
  290. if self.tail:
  291. previous = self.getprevious()
  292. if previous is None:
  293. parent.text = (parent.text or '') + self.tail
  294. else:
  295. previous.tail = (previous.tail or '') + self.tail
  296. parent.remove(self)
  297. def drop_tag(self):
  298. """
  299. Remove the tag, but not its children or text. The children and text
  300. are merged into the parent.
  301. Example::
  302. >>> h = fragment_fromstring('<div>Hello <b>World!</b></div>')
  303. >>> h.find('.//b').drop_tag()
  304. >>> print(tostring(h, encoding='unicode'))
  305. <div>Hello World!</div>
  306. """
  307. parent = self.getparent()
  308. assert parent is not None
  309. previous = self.getprevious()
  310. if self.text and isinstance(self.tag, basestring):
  311. # not a Comment, etc.
  312. if previous is None:
  313. parent.text = (parent.text or '') + self.text
  314. else:
  315. previous.tail = (previous.tail or '') + self.text
  316. if self.tail:
  317. if len(self):
  318. last = self[-1]
  319. last.tail = (last.tail or '') + self.tail
  320. elif previous is None:
  321. parent.text = (parent.text or '') + self.tail
  322. else:
  323. previous.tail = (previous.tail or '') + self.tail
  324. index = parent.index(self)
  325. parent[index:index+1] = self[:]
  326. def find_rel_links(self, rel):
  327. """
  328. Find any links like ``<a rel="{rel}">...</a>``; returns a list of elements.
  329. """
  330. rel = rel.lower()
  331. return [el for el in _rel_links_xpath(self)
  332. if el.get('rel').lower() == rel]
  333. def find_class(self, class_name):
  334. """
  335. Find any elements with the given class name.
  336. """
  337. return _class_xpath(self, class_name=class_name)
  338. def get_element_by_id(self, id, *default):
  339. """
  340. Get the first element in a document with the given id. If none is
  341. found, return the default argument if provided or raise KeyError
  342. otherwise.
  343. Note that there can be more than one element with the same id,
  344. and this isn't uncommon in HTML documents found in the wild.
  345. Browsers return only the first match, and this function does
  346. the same.
  347. """
  348. try:
  349. # FIXME: should this check for multiple matches?
  350. # browsers just return the first one
  351. return _id_xpath(self, id=id)[0]
  352. except IndexError:
  353. if default:
  354. return default[0]
  355. else:
  356. raise KeyError(id)
  357. def text_content(self):
  358. """
  359. Return the text content of the tag (and the text in any children).
  360. """
  361. return _collect_string_content(self)
  362. def cssselect(self, expr, translator='html'):
  363. """
  364. Run the CSS expression on this element and its children,
  365. returning a list of the results.
  366. Equivalent to lxml.cssselect.CSSSelect(expr, translator='html')(self)
  367. -- note that pre-compiling the expression can provide a substantial
  368. speedup.
  369. """
  370. # Do the import here to make the dependency optional.
  371. from lxml.cssselect import CSSSelector
  372. return CSSSelector(expr, translator=translator)(self)
  373. ########################################
  374. ## Link functions
  375. ########################################
  376. def make_links_absolute(self, base_url=None, resolve_base_href=True,
  377. handle_failures=None):
  378. """
  379. Make all links in the document absolute, given the
  380. ``base_url`` for the document (the full URL where the document
  381. came from), or if no ``base_url`` is given, then the ``.base_url``
  382. of the document.
  383. If ``resolve_base_href`` is true, then any ``<base href>``
  384. tags in the document are used *and* removed from the document.
  385. If it is false then any such tag is ignored.
  386. If ``handle_failures`` is None (default), a failure to process
  387. a URL will abort the processing. If set to 'ignore', errors
  388. are ignored. If set to 'discard', failing URLs will be removed.
  389. """
  390. if base_url is None:
  391. base_url = self.base_url
  392. if base_url is None:
  393. raise TypeError(
  394. "No base_url given, and the document has no base_url")
  395. if resolve_base_href:
  396. self.resolve_base_href()
  397. if handle_failures == 'ignore':
  398. def link_repl(href):
  399. try:
  400. return urljoin(base_url, href)
  401. except ValueError:
  402. return href
  403. elif handle_failures == 'discard':
  404. def link_repl(href):
  405. try:
  406. return urljoin(base_url, href)
  407. except ValueError:
  408. return None
  409. elif handle_failures is None:
  410. def link_repl(href):
  411. return urljoin(base_url, href)
  412. else:
  413. raise ValueError(
  414. "unexpected value for handle_failures: %r" % handle_failures)
  415. self.rewrite_links(link_repl)
  416. def resolve_base_href(self, handle_failures=None):
  417. """
  418. Find any ``<base href>`` tag in the document, and apply its
  419. values to all links found in the document. Also remove the
  420. tag once it has been applied.
  421. If ``handle_failures`` is None (default), a failure to process
  422. a URL will abort the processing. If set to 'ignore', errors
  423. are ignored. If set to 'discard', failing URLs will be removed.
  424. """
  425. base_href = None
  426. basetags = self.xpath('//base[@href]|//x:base[@href]',
  427. namespaces={'x': XHTML_NAMESPACE})
  428. for b in basetags:
  429. base_href = b.get('href')
  430. b.drop_tree()
  431. if not base_href:
  432. return
  433. self.make_links_absolute(base_href, resolve_base_href=False,
  434. handle_failures=handle_failures)
  435. def iterlinks(self):
  436. """
  437. Yield (element, attribute, link, pos), where attribute may be None
  438. (indicating the link is in the text). ``pos`` is the position
  439. where the link occurs; often 0, but sometimes something else in
  440. the case of links in stylesheets or style tags.
  441. Note: <base href> is *not* taken into account in any way. The
  442. link you get is exactly the link in the document.
  443. Note: multiple links inside of a single text string or
  444. attribute value are returned in reversed order. This makes it
  445. possible to replace or delete them from the text string value
  446. based on their reported text positions. Otherwise, a
  447. modification at one text position can change the positions of
  448. links reported later on.
  449. """
  450. link_attrs = defs.link_attrs
  451. for el in self.iter(etree.Element):
  452. attribs = el.attrib
  453. tag = _nons(el.tag)
  454. if tag == 'object':
  455. codebase = None
  456. ## <object> tags have attributes that are relative to
  457. ## codebase
  458. if 'codebase' in attribs:
  459. codebase = el.get('codebase')
  460. yield (el, 'codebase', codebase, 0)
  461. for attrib in ('classid', 'data'):
  462. if attrib in attribs:
  463. value = el.get(attrib)
  464. if codebase is not None:
  465. value = urljoin(codebase, value)
  466. yield (el, attrib, value, 0)
  467. if 'archive' in attribs:
  468. for match in _archive_re.finditer(el.get('archive')):
  469. value = match.group(0)
  470. if codebase is not None:
  471. value = urljoin(codebase, value)
  472. yield (el, 'archive', value, match.start())
  473. else:
  474. for attrib in link_attrs:
  475. if attrib in attribs:
  476. yield (el, attrib, attribs[attrib], 0)
  477. if tag == 'meta':
  478. http_equiv = attribs.get('http-equiv', '').lower()
  479. if http_equiv == 'refresh':
  480. content = attribs.get('content', '')
  481. match = _parse_meta_refresh_url(content)
  482. url = (match.group('url') if match else content).strip()
  483. # unexpected content means the redirect won't work, but we might
  484. # as well be permissive and return the entire string.
  485. if url:
  486. url, pos = _unquote_match(
  487. url, match.start('url') if match else content.find(url))
  488. yield (el, 'content', url, pos)
  489. elif tag == 'param':
  490. valuetype = el.get('valuetype') or ''
  491. if valuetype.lower() == 'ref':
  492. ## FIXME: while it's fine we *find* this link,
  493. ## according to the spec we aren't supposed to
  494. ## actually change the value, including resolving
  495. ## it. It can also still be a link, even if it
  496. ## doesn't have a valuetype="ref" (which seems to be the norm)
  497. ## http://www.w3.org/TR/html401/struct/objects.html#adef-valuetype
  498. yield (el, 'value', el.get('value'), 0)
  499. elif tag == 'style' and el.text:
  500. urls = [
  501. # (start_pos, url)
  502. _unquote_match(match.group(1), match.start(1))[::-1]
  503. for match in _iter_css_urls(el.text)
  504. ] + [
  505. (match.start(1), match.group(1))
  506. for match in _iter_css_imports(el.text)
  507. ]
  508. if urls:
  509. # sort by start pos to bring both match sets back into order
  510. # and reverse the list to report correct positions despite
  511. # modifications
  512. urls.sort(reverse=True)
  513. for start, url in urls:
  514. yield (el, None, url, start)
  515. if 'style' in attribs:
  516. urls = list(_iter_css_urls(attribs['style']))
  517. if urls:
  518. # return in reversed order to simplify in-place modifications
  519. for match in urls[::-1]:
  520. url, start = _unquote_match(match.group(1), match.start(1))
  521. yield (el, 'style', url, start)
  522. def rewrite_links(self, link_repl_func, resolve_base_href=True,
  523. base_href=None):
  524. """
  525. Rewrite all the links in the document. For each link
  526. ``link_repl_func(link)`` will be called, and the return value
  527. will replace the old link.
  528. Note that links may not be absolute (unless you first called
  529. ``make_links_absolute()``), and may be internal (e.g.,
  530. ``'#anchor'``). They can also be values like
  531. ``'mailto:email'`` or ``'javascript:expr'``.
  532. If you give ``base_href`` then all links passed to
  533. ``link_repl_func()`` will take that into account.
  534. If the ``link_repl_func`` returns None, the attribute or
  535. tag text will be removed completely.
  536. """
  537. if base_href is not None:
  538. # FIXME: this can be done in one pass with a wrapper
  539. # around link_repl_func
  540. self.make_links_absolute(
  541. base_href, resolve_base_href=resolve_base_href)
  542. elif resolve_base_href:
  543. self.resolve_base_href()
  544. for el, attrib, link, pos in self.iterlinks():
  545. new_link = link_repl_func(link.strip())
  546. if new_link == link:
  547. continue
  548. if new_link is None:
  549. # Remove the attribute or element content
  550. if attrib is None:
  551. el.text = ''
  552. else:
  553. del el.attrib[attrib]
  554. continue
  555. if attrib is None:
  556. new = el.text[:pos] + new_link + el.text[pos+len(link):]
  557. el.text = new
  558. else:
  559. cur = el.get(attrib)
  560. if not pos and len(cur) == len(link):
  561. new = new_link # most common case
  562. else:
  563. new = cur[:pos] + new_link + cur[pos+len(link):]
  564. el.set(attrib, new)
  565. class _MethodFunc(object):
  566. """
  567. An object that represents a method on an element as a function;
  568. the function takes either an element or an HTML string. It
  569. returns whatever the function normally returns, or if the function
  570. works in-place (and so returns None) it returns a serialized form
  571. of the resulting document.
  572. """
  573. def __init__(self, name, copy=False, source_class=HtmlMixin):
  574. self.name = name
  575. self.copy = copy
  576. self.__doc__ = getattr(source_class, self.name).__doc__
  577. def __call__(self, doc, *args, **kw):
  578. result_type = type(doc)
  579. if isinstance(doc, basestring):
  580. if 'copy' in kw:
  581. raise TypeError(
  582. "The keyword 'copy' can only be used with element inputs to %s, not a string input" % self.name)
  583. doc = fromstring(doc, **kw)
  584. else:
  585. if 'copy' in kw:
  586. make_a_copy = kw.pop('copy')
  587. else:
  588. make_a_copy = self.copy
  589. if make_a_copy:
  590. doc = copy.deepcopy(doc)
  591. meth = getattr(doc, self.name)
  592. result = meth(*args, **kw)
  593. # FIXME: this None test is a bit sloppy
  594. if result is None:
  595. # Then return what we got in
  596. return _transform_result(result_type, doc)
  597. else:
  598. return result
  599. find_rel_links = _MethodFunc('find_rel_links', copy=False)
  600. find_class = _MethodFunc('find_class', copy=False)
  601. make_links_absolute = _MethodFunc('make_links_absolute', copy=True)
  602. resolve_base_href = _MethodFunc('resolve_base_href', copy=True)
  603. iterlinks = _MethodFunc('iterlinks', copy=False)
  604. rewrite_links = _MethodFunc('rewrite_links', copy=True)
  605. class HtmlComment(etree.CommentBase, HtmlMixin):
  606. pass
  607. class HtmlElement(etree.ElementBase, HtmlMixin):
  608. # Override etree.ElementBase.cssselect() and set(), despite the MRO (FIXME: change base order?)
  609. cssselect = HtmlMixin.cssselect
  610. set = HtmlMixin.set
  611. class HtmlProcessingInstruction(etree.PIBase, HtmlMixin):
  612. pass
  613. class HtmlEntity(etree.EntityBase, HtmlMixin):
  614. pass
  615. class HtmlElementClassLookup(etree.CustomElementClassLookup):
  616. """A lookup scheme for HTML Element classes.
  617. To create a lookup instance with different Element classes, pass a tag
  618. name mapping of Element classes in the ``classes`` keyword argument and/or
  619. a tag name mapping of Mixin classes in the ``mixins`` keyword argument.
  620. The special key '*' denotes a Mixin class that should be mixed into all
  621. Element classes.
  622. """
  623. _default_element_classes = {}
  624. def __init__(self, classes=None, mixins=None):
  625. etree.CustomElementClassLookup.__init__(self)
  626. if classes is None:
  627. classes = self._default_element_classes.copy()
  628. if mixins:
  629. mixers = {}
  630. for name, value in mixins:
  631. if name == '*':
  632. for n in classes.keys():
  633. mixers.setdefault(n, []).append(value)
  634. else:
  635. mixers.setdefault(name, []).append(value)
  636. for name, mix_bases in mixers.items():
  637. cur = classes.get(name, HtmlElement)
  638. bases = tuple(mix_bases + [cur])
  639. classes[name] = type(cur.__name__, bases, {})
  640. self._element_classes = classes
  641. def lookup(self, node_type, document, namespace, name):
  642. if node_type == 'element':
  643. return self._element_classes.get(name.lower(), HtmlElement)
  644. elif node_type == 'comment':
  645. return HtmlComment
  646. elif node_type == 'PI':
  647. return HtmlProcessingInstruction
  648. elif node_type == 'entity':
  649. return HtmlEntity
  650. # Otherwise normal lookup
  651. return None
  652. ################################################################################
  653. # parsing
  654. ################################################################################
  655. _looks_like_full_html_unicode = re.compile(
  656. unicode(r'^\s*<(?:html|!doctype)'), re.I).match
  657. _looks_like_full_html_bytes = re.compile(
  658. r'^\s*<(?:html|!doctype)'.encode('ascii'), re.I).match
  659. def document_fromstring(html, parser=None, ensure_head_body=False, **kw):
  660. if parser is None:
  661. parser = html_parser
  662. value = etree.fromstring(html, parser, **kw)
  663. if value is None:
  664. raise etree.ParserError(
  665. "Document is empty")
  666. if ensure_head_body and value.find('head') is None:
  667. value.insert(0, Element('head'))
  668. if ensure_head_body and value.find('body') is None:
  669. value.append(Element('body'))
  670. return value
  671. def fragments_fromstring(html, no_leading_text=False, base_url=None,
  672. parser=None, **kw):
  673. """Parses several HTML elements, returning a list of elements.
  674. The first item in the list may be a string.
  675. If no_leading_text is true, then it will be an error if there is
  676. leading text, and it will always be a list of only elements.
  677. base_url will set the document's base_url attribute
  678. (and the tree's docinfo.URL).
  679. """
  680. if parser is None:
  681. parser = html_parser
  682. # FIXME: check what happens when you give html with a body, head, etc.
  683. if isinstance(html, bytes):
  684. if not _looks_like_full_html_bytes(html):
  685. # can't use %-formatting in early Py3 versions
  686. html = ('<html><body>'.encode('ascii') + html +
  687. '</body></html>'.encode('ascii'))
  688. else:
  689. if not _looks_like_full_html_unicode(html):
  690. html = '<html><body>%s</body></html>' % html
  691. doc = document_fromstring(html, parser=parser, base_url=base_url, **kw)
  692. assert _nons(doc.tag) == 'html'
  693. bodies = [e for e in doc if _nons(e.tag) == 'body']
  694. assert len(bodies) == 1, ("too many bodies: %r in %r" % (bodies, html))
  695. body = bodies[0]
  696. elements = []
  697. if no_leading_text and body.text and body.text.strip():
  698. raise etree.ParserError(
  699. "There is leading text: %r" % body.text)
  700. if body.text and body.text.strip():
  701. elements.append(body.text)
  702. elements.extend(body)
  703. # FIXME: removing the reference to the parent artificial document
  704. # would be nice
  705. return elements
  706. def fragment_fromstring(html, create_parent=False, base_url=None,
  707. parser=None, **kw):
  708. """
  709. Parses a single HTML element; it is an error if there is more than
  710. one element, or if anything but whitespace precedes or follows the
  711. element.
  712. If ``create_parent`` is true (or is a tag name) then a parent node
  713. will be created to encapsulate the HTML in a single element. In this
  714. case, leading or trailing text is also allowed, as are multiple elements
  715. as result of the parsing.
  716. Passing a ``base_url`` will set the document's ``base_url`` attribute
  717. (and the tree's docinfo.URL).
  718. """
  719. if parser is None:
  720. parser = html_parser
  721. accept_leading_text = bool(create_parent)
  722. elements = fragments_fromstring(
  723. html, parser=parser, no_leading_text=not accept_leading_text,
  724. base_url=base_url, **kw)
  725. if create_parent:
  726. if not isinstance(create_parent, basestring):
  727. create_parent = 'div'
  728. new_root = Element(create_parent)
  729. if elements:
  730. if isinstance(elements[0], basestring):
  731. new_root.text = elements[0]
  732. del elements[0]
  733. new_root.extend(elements)
  734. return new_root
  735. if not elements:
  736. raise etree.ParserError('No elements found')
  737. if len(elements) > 1:
  738. raise etree.ParserError(
  739. "Multiple elements found (%s)"
  740. % ', '.join([_element_name(e) for e in elements]))
  741. el = elements[0]
  742. if el.tail and el.tail.strip():
  743. raise etree.ParserError(
  744. "Element followed by text: %r" % el.tail)
  745. el.tail = None
  746. return el
  747. def fromstring(html, base_url=None, parser=None, **kw):
  748. """
  749. Parse the html, returning a single element/document.
  750. This tries to minimally parse the chunk of text, without knowing if it
  751. is a fragment or a document.
  752. base_url will set the document's base_url attribute (and the tree's docinfo.URL)
  753. """
  754. if parser is None:
  755. parser = html_parser
  756. if isinstance(html, bytes):
  757. is_full_html = _looks_like_full_html_bytes(html)
  758. else:
  759. is_full_html = _looks_like_full_html_unicode(html)
  760. doc = document_fromstring(html, parser=parser, base_url=base_url, **kw)
  761. if is_full_html:
  762. return doc
  763. # otherwise, lets parse it out...
  764. bodies = doc.findall('body')
  765. if not bodies:
  766. bodies = doc.findall('{%s}body' % XHTML_NAMESPACE)
  767. if bodies:
  768. body = bodies[0]
  769. if len(bodies) > 1:
  770. # Somehow there are multiple bodies, which is bad, but just
  771. # smash them into one body
  772. for other_body in bodies[1:]:
  773. if other_body.text:
  774. if len(body):
  775. body[-1].tail = (body[-1].tail or '') + other_body.text
  776. else:
  777. body.text = (body.text or '') + other_body.text
  778. body.extend(other_body)
  779. # We'll ignore tail
  780. # I guess we are ignoring attributes too
  781. other_body.drop_tree()
  782. else:
  783. body = None
  784. heads = doc.findall('head')
  785. if not heads:
  786. heads = doc.findall('{%s}head' % XHTML_NAMESPACE)
  787. if heads:
  788. # Well, we have some sort of structure, so lets keep it all
  789. head = heads[0]
  790. if len(heads) > 1:
  791. for other_head in heads[1:]:
  792. head.extend(other_head)
  793. # We don't care about text or tail in a head
  794. other_head.drop_tree()
  795. return doc
  796. if body is None:
  797. return doc
  798. if (len(body) == 1 and (not body.text or not body.text.strip())
  799. and (not body[-1].tail or not body[-1].tail.strip())):
  800. # The body has just one element, so it was probably a single
  801. # element passed in
  802. return body[0]
  803. # Now we have a body which represents a bunch of tags which have the
  804. # content that was passed in. We will create a fake container, which
  805. # is the body tag, except <body> implies too much structure.
  806. if _contains_block_level_tag(body):
  807. body.tag = 'div'
  808. else:
  809. body.tag = 'span'
  810. return body
  811. def parse(filename_or_url, parser=None, base_url=None, **kw):
  812. """
  813. Parse a filename, URL, or file-like object into an HTML document
  814. tree. Note: this returns a tree, not an element. Use
  815. ``parse(...).getroot()`` to get the document root.
  816. You can override the base URL with the ``base_url`` keyword. This
  817. is most useful when parsing from a file-like object.
  818. """
  819. if parser is None:
  820. parser = html_parser
  821. return etree.parse(filename_or_url, parser, base_url=base_url, **kw)
  822. def _contains_block_level_tag(el):
  823. # FIXME: I could do this with XPath, but would that just be
  824. # unnecessarily slow?
  825. for el in el.iter(etree.Element):
  826. if _nons(el.tag) in defs.block_tags:
  827. return True
  828. return False
  829. def _element_name(el):
  830. if isinstance(el, etree.CommentBase):
  831. return 'comment'
  832. elif isinstance(el, basestring):
  833. return 'string'
  834. else:
  835. return _nons(el.tag)
  836. ################################################################################
  837. # form handling
  838. ################################################################################
  839. class FormElement(HtmlElement):
  840. """
  841. Represents a <form> element.
  842. """
  843. @property
  844. def inputs(self):
  845. """
  846. Returns an accessor for all the input elements in the form.
  847. See `InputGetter` for more information about the object.
  848. """
  849. return InputGetter(self)
  850. @property
  851. def fields(self):
  852. """
  853. Dictionary-like object that represents all the fields in this
  854. form. You can set values in this dictionary to effect the
  855. form.
  856. """
  857. return FieldsDict(self.inputs)
  858. @fields.setter
  859. def fields(self, value):
  860. fields = self.fields
  861. prev_keys = fields.keys()
  862. for key, value in value.items():
  863. if key in prev_keys:
  864. prev_keys.remove(key)
  865. fields[key] = value
  866. for key in prev_keys:
  867. if key is None:
  868. # Case of an unnamed input; these aren't really
  869. # expressed in form_values() anyway.
  870. continue
  871. fields[key] = None
  872. def _name(self):
  873. if self.get('name'):
  874. return self.get('name')
  875. elif self.get('id'):
  876. return '#' + self.get('id')
  877. iter_tags = self.body.iter
  878. forms = list(iter_tags('form'))
  879. if not forms:
  880. forms = list(iter_tags('{%s}form' % XHTML_NAMESPACE))
  881. return str(forms.index(self))
  882. def form_values(self):
  883. """
  884. Return a list of tuples of the field values for the form.
  885. This is suitable to be passed to ``urllib.urlencode()``.
  886. """
  887. results = []
  888. for el in self.inputs:
  889. name = el.name
  890. if not name or 'disabled' in el.attrib:
  891. continue
  892. tag = _nons(el.tag)
  893. if tag == 'textarea':
  894. results.append((name, el.value))
  895. elif tag == 'select':
  896. value = el.value
  897. if el.multiple:
  898. for v in value:
  899. results.append((name, v))
  900. elif value is not None:
  901. results.append((name, el.value))
  902. else:
  903. assert tag == 'input', (
  904. "Unexpected tag: %r" % el)
  905. if el.checkable and not el.checked:
  906. continue
  907. if el.type in ('submit', 'image', 'reset', 'file'):
  908. continue
  909. value = el.value
  910. if value is not None:
  911. results.append((name, el.value))
  912. return results
  913. @property
  914. def action(self):
  915. """
  916. Get/set the form's ``action`` attribute.
  917. """
  918. base_url = self.base_url
  919. action = self.get('action')
  920. if base_url and action is not None:
  921. return urljoin(base_url, action)
  922. else:
  923. return action
  924. @action.setter
  925. def action(self, value):
  926. self.set('action', value)
  927. @action.deleter
  928. def action(self):
  929. attrib = self.attrib
  930. if 'action' in attrib:
  931. del attrib['action']
  932. @property
  933. def method(self):
  934. """
  935. Get/set the form's method. Always returns a capitalized
  936. string, and defaults to ``'GET'``
  937. """
  938. return self.get('method', 'GET').upper()
  939. @method.setter
  940. def method(self, value):
  941. self.set('method', value.upper())
  942. HtmlElementClassLookup._default_element_classes['form'] = FormElement
  943. def submit_form(form, extra_values=None, open_http=None):
  944. """
  945. Helper function to submit a form. Returns a file-like object, as from
  946. ``urllib.urlopen()``. This object also has a ``.geturl()`` function,
  947. which shows the URL if there were any redirects.
  948. You can use this like::
  949. form = doc.forms[0]
  950. form.inputs['foo'].value = 'bar' # etc
  951. response = form.submit()
  952. doc = parse(response)
  953. doc.make_links_absolute(response.geturl())
  954. To change the HTTP requester, pass a function as ``open_http`` keyword
  955. argument that opens the URL for you. The function must have the following
  956. signature::
  957. open_http(method, URL, values)
  958. The action is one of 'GET' or 'POST', the URL is the target URL as a
  959. string, and the values are a sequence of ``(name, value)`` tuples with the
  960. form data.
  961. """
  962. values = form.form_values()
  963. if extra_values:
  964. if hasattr(extra_values, 'items'):
  965. extra_values = extra_values.items()
  966. values.extend(extra_values)
  967. if open_http is None:
  968. open_http = open_http_urllib
  969. if form.action:
  970. url = form.action
  971. else:
  972. url = form.base_url
  973. return open_http(form.method, url, values)
  974. def open_http_urllib(method, url, values):
  975. if not url:
  976. raise ValueError("cannot submit, no URL provided")
  977. ## FIXME: should test that it's not a relative URL or something
  978. try:
  979. from urllib import urlencode, urlopen
  980. except ImportError: # Python 3
  981. from urllib.request import urlopen
  982. from urllib.parse import urlencode
  983. if method == 'GET':
  984. if '?' in url:
  985. url += '&'
  986. else:
  987. url += '?'
  988. url += urlencode(values)
  989. data = None
  990. else:
  991. data = urlencode(values)
  992. if not isinstance(data, bytes):
  993. data = data.encode('ASCII')
  994. return urlopen(url, data)
  995. class FieldsDict(MutableMapping):
  996. def __init__(self, inputs):
  997. self.inputs = inputs
  998. def __getitem__(self, item):
  999. return self.inputs[item].value
  1000. def __setitem__(self, item, value):
  1001. self.inputs[item].value = value
  1002. def __delitem__(self, item):
  1003. raise KeyError(
  1004. "You cannot remove keys from ElementDict")
  1005. def keys(self):
  1006. return self.inputs.keys()
  1007. def __contains__(self, item):
  1008. return item in self.inputs
  1009. def __iter__(self):
  1010. return iter(self.inputs.keys())
  1011. def __len__(self):
  1012. return len(self.inputs)
  1013. def __repr__(self):
  1014. return '<%s for form %s>' % (
  1015. self.__class__.__name__,
  1016. self.inputs.form._name())
  1017. class InputGetter(object):
  1018. """
  1019. An accessor that represents all the input fields in a form.
  1020. You can get fields by name from this, with
  1021. ``form.inputs['field_name']``. If there are a set of checkboxes
  1022. with the same name, they are returned as a list (a `CheckboxGroup`
  1023. which also allows value setting). Radio inputs are handled
  1024. similarly.
  1025. You can also iterate over this to get all input elements. This
  1026. won't return the same thing as if you get all the names, as
  1027. checkboxes and radio elements are returned individually.
  1028. """
  1029. _name_xpath = etree.XPath(".//*[@name = $name and (local-name(.) = 'select' or local-name(.) = 'input' or local-name(.) = 'textarea')]")
  1030. _all_xpath = etree.XPath(".//*[local-name() = 'select' or local-name() = 'input' or local-name() = 'textarea']")
  1031. def __init__(self, form):
  1032. self.form = form
  1033. def __repr__(self):
  1034. return '<%s for form %s>' % (
  1035. self.__class__.__name__,
  1036. self.form._name())
  1037. ## FIXME: there should be more methods, and it's unclear if this is
  1038. ## a dictionary-like object or list-like object
  1039. def __getitem__(self, name):
  1040. results = self._name_xpath(self.form, name=name)
  1041. if results:
  1042. type = results[0].get('type')
  1043. if type == 'radio' and len(results) > 1:
  1044. group = RadioGroup(results)
  1045. group.name = name
  1046. return group
  1047. elif type == 'checkbox' and len(results) > 1:
  1048. group = CheckboxGroup(results)
  1049. group.name = name
  1050. return group
  1051. else:
  1052. # I don't like throwing away elements like this
  1053. return results[0]
  1054. else:
  1055. raise KeyError(
  1056. "No input element with the name %r" % name)
  1057. def __contains__(self, name):
  1058. results = self._name_xpath(self.form, name=name)
  1059. return bool(results)
  1060. def keys(self):
  1061. names = set()
  1062. for el in self:
  1063. names.add(el.name)
  1064. if None in names:
  1065. names.remove(None)
  1066. return list(names)
  1067. def __iter__(self):
  1068. ## FIXME: kind of dumb to turn a list into an iterator, only
  1069. ## to have it likely turned back into a list again :(
  1070. return iter(self._all_xpath(self.form))
  1071. class InputMixin(object):
  1072. """
  1073. Mix-in for all input elements (input, select, and textarea)
  1074. """
  1075. @property
  1076. def name(self):
  1077. """
  1078. Get/set the name of the element
  1079. """
  1080. return self.get('name')
  1081. @name.setter
  1082. def name(self, value):
  1083. self.set('name', value)
  1084. @name.deleter
  1085. def name(self):
  1086. attrib = self.attrib
  1087. if 'name' in attrib:
  1088. del attrib['name']
  1089. def __repr__(self):
  1090. type_name = getattr(self, 'type', None)
  1091. if type_name:
  1092. type_name = ' type=%r' % type_name
  1093. else:
  1094. type_name = ''
  1095. return '<%s %x name=%r%s>' % (
  1096. self.__class__.__name__, id(self), self.name, type_name)
  1097. class TextareaElement(InputMixin, HtmlElement):
  1098. """
  1099. ``<textarea>`` element. You can get the name with ``.name`` and
  1100. get/set the value with ``.value``
  1101. """
  1102. @property
  1103. def value(self):
  1104. """
  1105. Get/set the value (which is the contents of this element)
  1106. """
  1107. content = self.text or ''
  1108. if self.tag.startswith("{%s}" % XHTML_NAMESPACE):
  1109. serialisation_method = 'xml'
  1110. else:
  1111. serialisation_method = 'html'
  1112. for el in self:
  1113. # it's rare that we actually get here, so let's not use ''.join()
  1114. content += etree.tostring(
  1115. el, method=serialisation_method, encoding='unicode')
  1116. return content
  1117. @value.setter
  1118. def value(self, value):
  1119. del self[:]
  1120. self.text = value
  1121. @value.deleter
  1122. def value(self):
  1123. self.text = ''
  1124. del self[:]
  1125. HtmlElementClassLookup._default_element_classes['textarea'] = TextareaElement
  1126. class SelectElement(InputMixin, HtmlElement):
  1127. """
  1128. ``<select>`` element. You can get the name with ``.name``.
  1129. ``.value`` will be the value of the selected option, unless this
  1130. is a multi-select element (``<select multiple>``), in which case
  1131. it will be a set-like object. In either case ``.value_options``
  1132. gives the possible values.
  1133. The boolean attribute ``.multiple`` shows if this is a
  1134. multi-select.
  1135. """
  1136. @property
  1137. def value(self):
  1138. """
  1139. Get/set the value of this select (the selected option).
  1140. If this is a multi-select, this is a set-like object that
  1141. represents all the selected options.
  1142. """
  1143. if self.multiple:
  1144. return MultipleSelectOptions(self)
  1145. options = _options_xpath(self)
  1146. try:
  1147. selected_option = next(el for el in reversed(options) if el.get('selected') is not None)
  1148. except StopIteration:
  1149. try:
  1150. selected_option = next(el for el in options if el.get('disabled') is None)
  1151. except StopIteration:
  1152. return None
  1153. value = selected_option.get('value')
  1154. if value is None:
  1155. value = (selected_option.text or '').strip()
  1156. return value
  1157. @value.setter
  1158. def value(self, value):
  1159. if self.multiple:
  1160. if isinstance(value, basestring):
  1161. raise TypeError("You must pass in a sequence")
  1162. values = self.value
  1163. values.clear()
  1164. values.update(value)
  1165. return
  1166. checked_option = None
  1167. if value is not None:
  1168. for el in _options_xpath(self):
  1169. opt_value = el.get('value')
  1170. if opt_value is None:
  1171. opt_value = (el.text or '').strip()
  1172. if opt_value == value:
  1173. checked_option = el
  1174. break
  1175. else:
  1176. raise ValueError(
  1177. "There is no option with the value of %r" % value)
  1178. for el in _options_xpath(self):
  1179. if 'selected' in el.attrib:
  1180. del el.attrib['selected']
  1181. if checked_option is not None:
  1182. checked_option.set('selected', '')
  1183. @value.deleter
  1184. def value(self):
  1185. # FIXME: should del be allowed at all?
  1186. if self.multiple:
  1187. self.value.clear()
  1188. else:
  1189. self.value = None
  1190. @property
  1191. def value_options(self):
  1192. """
  1193. All the possible values this select can have (the ``value``
  1194. attribute of all the ``<option>`` elements.
  1195. """
  1196. options = []
  1197. for el in _options_xpath(self):
  1198. value = el.get('value')
  1199. if value is None:
  1200. value = (el.text or '').strip()
  1201. options.append(value)
  1202. return options
  1203. @property
  1204. def multiple(self):
  1205. """
  1206. Boolean attribute: is there a ``multiple`` attribute on this element.
  1207. """
  1208. return 'multiple' in self.attrib
  1209. @multiple.setter
  1210. def multiple(self, value):
  1211. if value:
  1212. self.set('multiple', '')
  1213. elif 'multiple' in self.attrib:
  1214. del self.attrib['multiple']
  1215. HtmlElementClassLookup._default_element_classes['select'] = SelectElement
  1216. class MultipleSelectOptions(SetMixin):
  1217. """
  1218. Represents all the selected options in a ``<select multiple>`` element.
  1219. You can add to this set-like option to select an option, or remove
  1220. to unselect the option.
  1221. """
  1222. def __init__(self, select):
  1223. self.select = select
  1224. @property
  1225. def options(self):
  1226. """
  1227. Iterator of all the ``<option>`` elements.
  1228. """
  1229. return iter(_options_xpath(self.select))
  1230. def __iter__(self):
  1231. for option in self.options:
  1232. if 'selected' in option.attrib:
  1233. opt_value = option.get('value')
  1234. if opt_value is None:
  1235. opt_value = (option.text or '').strip()
  1236. yield opt_value
  1237. def add(self, item):
  1238. for option in self.options:
  1239. opt_value = option.get('value')
  1240. if opt_value is None:
  1241. opt_value = (option.text or '').strip()
  1242. if opt_value == item:
  1243. option.set('selected', '')
  1244. break
  1245. else:
  1246. raise ValueError(
  1247. "There is no option with the value %r" % item)
  1248. def remove(self, item):
  1249. for option in self.options:
  1250. opt_value = option.get('value')
  1251. if opt_value is None:
  1252. opt_value = (option.text or '').strip()
  1253. if opt_value == item:
  1254. if 'selected' in option.attrib:
  1255. del option.attrib['selected']
  1256. else:
  1257. raise ValueError(
  1258. "The option %r is not currently selected" % item)
  1259. break
  1260. else:
  1261. raise ValueError(
  1262. "There is not option with the value %r" % item)
  1263. def __repr__(self):
  1264. return '<%s {%s} for select name=%r>' % (
  1265. self.__class__.__name__,
  1266. ', '.join([repr(v) for v in self]),
  1267. self.select.name)
  1268. class RadioGroup(list):
  1269. """
  1270. This object represents several ``<input type=radio>`` elements
  1271. that have the same name.
  1272. You can use this like a list, but also use the property
  1273. ``.value`` to check/uncheck inputs. Also you can use
  1274. ``.value_options`` to get the possible values.
  1275. """
  1276. @property
  1277. def value(self):
  1278. """
  1279. Get/set the value, which checks the radio with that value (and
  1280. unchecks any other value).
  1281. """
  1282. for el in self:
  1283. if 'checked' in el.attrib:
  1284. return el.get('value')
  1285. return None
  1286. @value.setter
  1287. def value(self, value):
  1288. checked_option = None
  1289. if value is not None:
  1290. for el in self:
  1291. if el.get('value') == value:
  1292. checked_option = el
  1293. break
  1294. else:
  1295. raise ValueError("There is no radio input with the value %r" % value)
  1296. for el in self:
  1297. if 'checked' in el.attrib:
  1298. del el.attrib['checked']
  1299. if checked_option is not None:
  1300. checked_option.set('checked', '')
  1301. @value.deleter
  1302. def value(self):
  1303. self.value = None
  1304. @property
  1305. def value_options(self):
  1306. """
  1307. Returns a list of all the possible values.
  1308. """
  1309. return [el.get('value') for el in self]
  1310. def __repr__(self):
  1311. return '%s(%s)' % (
  1312. self.__class__.__name__,
  1313. list.__repr__(self))
  1314. class CheckboxGroup(list):
  1315. """
  1316. Represents a group of checkboxes (``<input type=checkbox>``) that
  1317. have the same name.
  1318. In addition to using this like a list, the ``.value`` attribute
  1319. returns a set-like object that you can add to or remove from to
  1320. check and uncheck checkboxes. You can also use ``.value_options``
  1321. to get the possible values.
  1322. """
  1323. @property
  1324. def value(self):
  1325. """
  1326. Return a set-like object that can be modified to check or
  1327. uncheck individual checkboxes according to their value.
  1328. """
  1329. return CheckboxValues(self)
  1330. @value.setter
  1331. def value(self, value):
  1332. values = self.value
  1333. values.clear()
  1334. if not hasattr(value, '__iter__'):
  1335. raise ValueError(
  1336. "A CheckboxGroup (name=%r) must be set to a sequence (not %r)"
  1337. % (self[0].name, value))
  1338. values.update(value)
  1339. @value.deleter
  1340. def value(self):
  1341. self.value.clear()
  1342. @property
  1343. def value_options(self):
  1344. """
  1345. Returns a list of all the possible values.
  1346. """
  1347. return [el.get('value') for el in self]
  1348. def __repr__(self):
  1349. return '%s(%s)' % (
  1350. self.__class__.__name__, list.__repr__(self))
  1351. class CheckboxValues(SetMixin):
  1352. """
  1353. Represents the values of the checked checkboxes in a group of
  1354. checkboxes with the same name.
  1355. """
  1356. def __init__(self, group):
  1357. self.group = group
  1358. def __iter__(self):
  1359. return iter([
  1360. el.get('value')
  1361. for el in self.group
  1362. if 'checked' in el.attrib])
  1363. def add(self, value):
  1364. for el in self.group:
  1365. if el.get('value') == value:
  1366. el.set('checked', '')
  1367. break
  1368. else:
  1369. raise KeyError("No checkbox with value %r" % value)
  1370. def remove(self, value):
  1371. for el in self.group:
  1372. if el.get('value') == value:
  1373. if 'checked' in el.attrib:
  1374. del el.attrib['checked']
  1375. else:
  1376. raise KeyError(
  1377. "The checkbox with value %r was already unchecked" % value)
  1378. break
  1379. else:
  1380. raise KeyError(
  1381. "No checkbox with value %r" % value)
  1382. def __repr__(self):
  1383. return '<%s {%s} for checkboxes name=%r>' % (
  1384. self.__class__.__name__,
  1385. ', '.join([repr(v) for v in self]),
  1386. self.group.name)
  1387. class InputElement(InputMixin, HtmlElement):
  1388. """
  1389. Represents an ``<input>`` element.
  1390. You can get the type with ``.type`` (which is lower-cased and
  1391. defaults to ``'text'``).
  1392. Also you can get and set the value with ``.value``
  1393. Checkboxes and radios have the attribute ``input.checkable ==
  1394. True`` (for all others it is false) and a boolean attribute
  1395. ``.checked``.
  1396. """
  1397. ## FIXME: I'm a little uncomfortable with the use of .checked
  1398. @property
  1399. def value(self):
  1400. """
  1401. Get/set the value of this element, using the ``value`` attribute.
  1402. Also, if this is a checkbox and it has no value, this defaults
  1403. to ``'on'``. If it is a checkbox or radio that is not
  1404. checked, this returns None.
  1405. """
  1406. if self.checkable:
  1407. if self.checked:
  1408. return self.get('value') or 'on'
  1409. else:
  1410. return None
  1411. return self.get('value')
  1412. @value.setter
  1413. def value(self, value):
  1414. if self.checkable:
  1415. if not value:
  1416. self.checked = False
  1417. else:
  1418. self.checked = True
  1419. if isinstance(value, basestring):
  1420. self.set('value', value)
  1421. else:
  1422. self.set('value', value)
  1423. @value.deleter
  1424. def value(self):
  1425. if self.checkable:
  1426. self.checked = False
  1427. else:
  1428. if 'value' in self.attrib:
  1429. del self.attrib['value']
  1430. @property
  1431. def type(self):
  1432. """
  1433. Return the type of this element (using the type attribute).
  1434. """
  1435. return self.get('type', 'text').lower()
  1436. @type.setter
  1437. def type(self, value):
  1438. self.set('type', value)
  1439. @property
  1440. def checkable(self):
  1441. """
  1442. Boolean: can this element be checked?
  1443. """
  1444. return self.type in ('checkbox', 'radio')
  1445. @property
  1446. def checked(self):
  1447. """
  1448. Boolean attribute to get/set the presence of the ``checked``
  1449. attribute.
  1450. You can only use this on checkable input types.
  1451. """
  1452. if not self.checkable:
  1453. raise AttributeError('Not a checkable input type')
  1454. return 'checked' in self.attrib
  1455. @checked.setter
  1456. def checked(self, value):
  1457. if not self.checkable:
  1458. raise AttributeError('Not a checkable input type')
  1459. if value:
  1460. self.set('checked', '')
  1461. else:
  1462. attrib = self.attrib
  1463. if 'checked' in attrib:
  1464. del attrib['checked']
  1465. HtmlElementClassLookup._default_element_classes['input'] = InputElement
  1466. class LabelElement(HtmlElement):
  1467. """
  1468. Represents a ``<label>`` element.
  1469. Label elements are linked to other elements with their ``for``
  1470. attribute. You can access this element with ``label.for_element``.
  1471. """
  1472. @property
  1473. def for_element(self):
  1474. """
  1475. Get/set the element this label points to. Return None if it
  1476. can't be found.
  1477. """
  1478. id = self.get('for')
  1479. if not id:
  1480. return None
  1481. return self.body.get_element_by_id(id)
  1482. @for_element.setter
  1483. def for_element(self, other):
  1484. id = other.get('id')
  1485. if not id:
  1486. raise TypeError(
  1487. "Element %r has no id attribute" % other)
  1488. self.set('for', id)
  1489. @for_element.deleter
  1490. def for_element(self):
  1491. attrib = self.attrib
  1492. if 'id' in attrib:
  1493. del attrib['id']
  1494. HtmlElementClassLookup._default_element_classes['label'] = LabelElement
  1495. ############################################################
  1496. ## Serialization
  1497. ############################################################
  1498. def html_to_xhtml(html):
  1499. """Convert all tags in an HTML tree to XHTML by moving them to the
  1500. XHTML namespace.
  1501. """
  1502. try:
  1503. html = html.getroot()
  1504. except AttributeError:
  1505. pass
  1506. prefix = "{%s}" % XHTML_NAMESPACE
  1507. for el in html.iter(etree.Element):
  1508. tag = el.tag
  1509. if tag[0] != '{':
  1510. el.tag = prefix + tag
  1511. def xhtml_to_html(xhtml):
  1512. """Convert all tags in an XHTML tree to HTML by removing their
  1513. XHTML namespace.
  1514. """
  1515. try:
  1516. xhtml = xhtml.getroot()
  1517. except AttributeError:
  1518. pass
  1519. prefix = "{%s}" % XHTML_NAMESPACE
  1520. prefix_len = len(prefix)
  1521. for el in xhtml.iter(prefix + "*"):
  1522. el.tag = el.tag[prefix_len:]
  1523. # This isn't a general match, but it's a match for what libxml2
  1524. # specifically serialises:
  1525. __str_replace_meta_content_type = re.compile(
  1526. r'<meta http-equiv="Content-Type"[^>]*>').sub
  1527. __bytes_replace_meta_content_type = re.compile(
  1528. r'<meta http-equiv="Content-Type"[^>]*>'.encode('ASCII')).sub
  1529. def tostring(doc, pretty_print=False, include_meta_content_type=False,
  1530. encoding=None, method="html", with_tail=True, doctype=None):
  1531. """Return an HTML string representation of the document.
  1532. Note: if include_meta_content_type is true this will create a
  1533. ``<meta http-equiv="Content-Type" ...>`` tag in the head;
  1534. regardless of the value of include_meta_content_type any existing
  1535. ``<meta http-equiv="Content-Type" ...>`` tag will be removed
  1536. The ``encoding`` argument controls the output encoding (defauts to
  1537. ASCII, with &#...; character references for any characters outside
  1538. of ASCII). Note that you can pass the name ``'unicode'`` as
  1539. ``encoding`` argument to serialise to a Unicode string.
  1540. The ``method`` argument defines the output method. It defaults to
  1541. 'html', but can also be 'xml' for xhtml output, or 'text' to
  1542. serialise to plain text without markup.
  1543. To leave out the tail text of the top-level element that is being
  1544. serialised, pass ``with_tail=False``.
  1545. The ``doctype`` option allows passing in a plain string that will
  1546. be serialised before the XML tree. Note that passing in non
  1547. well-formed content here will make the XML output non well-formed.
  1548. Also, an existing doctype in the document tree will not be removed
  1549. when serialising an ElementTree instance.
  1550. Example::
  1551. >>> from lxml import html
  1552. >>> root = html.fragment_fromstring('<p>Hello<br>world!</p>')
  1553. >>> html.tostring(root)
  1554. b'<p>Hello<br>world!</p>'
  1555. >>> html.tostring(root, method='html')
  1556. b'<p>Hello<br>world!</p>'
  1557. >>> html.tostring(root, method='xml')
  1558. b'<p>Hello<br/>world!</p>'
  1559. >>> html.tostring(root, method='text')
  1560. b'Helloworld!'
  1561. >>> html.tostring(root, method='text', encoding='unicode')
  1562. u'Helloworld!'
  1563. >>> root = html.fragment_fromstring('<div><p>Hello<br>world!</p>TAIL</div>')
  1564. >>> html.tostring(root[0], method='text', encoding='unicode')
  1565. u'Helloworld!TAIL'
  1566. >>> html.tostring(root[0], method='text', encoding='unicode', with_tail=False)
  1567. u'Helloworld!'
  1568. >>> doc = html.document_fromstring('<p>Hello<br>world!</p>')
  1569. >>> html.tostring(doc, method='html', encoding='unicode')
  1570. u'<html><body><p>Hello<br>world!</p></body></html>'
  1571. >>> print(html.tostring(doc, method='html', encoding='unicode',
  1572. ... doctype='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'
  1573. ... ' "http://www.w3.org/TR/html4/strict.dtd">'))
  1574. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  1575. <html><body><p>Hello<br>world!</p></body></html>
  1576. """
  1577. html = etree.tostring(doc, method=method, pretty_print=pretty_print,
  1578. encoding=encoding, with_tail=with_tail,
  1579. doctype=doctype)
  1580. if method == 'html' and not include_meta_content_type:
  1581. if isinstance(html, str):
  1582. html = __str_replace_meta_content_type('', html)
  1583. else:
  1584. html = __bytes_replace_meta_content_type(bytes(), html)
  1585. return html
  1586. tostring.__doc__ = __fix_docstring(tostring.__doc__)
  1587. def open_in_browser(doc, encoding=None):
  1588. """
  1589. Open the HTML document in a web browser, saving it to a temporary
  1590. file to open it. Note that this does not delete the file after
  1591. use. This is mainly meant for debugging.
  1592. """
  1593. import os
  1594. import webbrowser
  1595. import tempfile
  1596. if not isinstance(doc, etree._ElementTree):
  1597. doc = etree.ElementTree(doc)
  1598. handle, fn = tempfile.mkstemp(suffix='.html')
  1599. f = os.fdopen(handle, 'wb')
  1600. try:
  1601. doc.write(f, method="html", encoding=encoding or doc.docinfo.encoding or "UTF-8")
  1602. finally:
  1603. # we leak the file itself here, but we should at least close it
  1604. f.close()
  1605. url = 'file://' + fn.replace(os.path.sep, '/')
  1606. print(url)
  1607. webbrowser.open(url)
  1608. ################################################################################
  1609. # configure Element class lookup
  1610. ################################################################################
  1611. class HTMLParser(etree.HTMLParser):
  1612. """An HTML parser that is configured to return lxml.html Element
  1613. objects.
  1614. """
  1615. def __init__(self, **kwargs):
  1616. super(HTMLParser, self).__init__(**kwargs)
  1617. self.set_element_class_lookup(HtmlElementClassLookup())
  1618. class XHTMLParser(etree.XMLParser):
  1619. """An XML parser that is configured to return lxml.html Element
  1620. objects.
  1621. Note that this parser is not really XHTML aware unless you let it
  1622. load a DTD that declares the HTML entities. To do this, make sure
  1623. you have the XHTML DTDs installed in your catalogs, and create the
  1624. parser like this::
  1625. >>> parser = XHTMLParser(load_dtd=True)
  1626. If you additionally want to validate the document, use this::
  1627. >>> parser = XHTMLParser(dtd_validation=True)
  1628. For catalog support, see http://www.xmlsoft.org/catalog.html.
  1629. """
  1630. def __init__(self, **kwargs):
  1631. super(XHTMLParser, self).__init__(**kwargs)
  1632. self.set_element_class_lookup(HtmlElementClassLookup())
  1633. def Element(*args, **kw):
  1634. """Create a new HTML Element.
  1635. This can also be used for XHTML documents.
  1636. """
  1637. v = html_parser.makeelement(*args, **kw)
  1638. return v
  1639. html_parser = HTMLParser()
  1640. xhtml_parser = XHTMLParser()