PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/web/lib/bs4/element.py

https://gitlab.com/adam.lukaitis/muzei
Python | 1334 lines | 1125 code | 59 blank | 150 comment | 79 complexity | 3dbd99492b35371eced27e87b881b421 MD5 | raw file
  1. import collections
  2. import re
  3. import sys
  4. import warnings
  5. from bs4.dammit import EntitySubstitution
  6. DEFAULT_OUTPUT_ENCODING = "utf-8"
  7. PY3K = (sys.version_info[0] > 2)
  8. whitespace_re = re.compile("\s+")
  9. def _alias(attr):
  10. """Alias one attribute name to another for backward compatibility"""
  11. @property
  12. def alias(self):
  13. return getattr(self, attr)
  14. @alias.setter
  15. def alias(self):
  16. return setattr(self, attr)
  17. return alias
  18. class NamespacedAttribute(unicode):
  19. def __new__(cls, prefix, name, namespace=None):
  20. if name is None:
  21. obj = unicode.__new__(cls, prefix)
  22. elif prefix is None:
  23. # Not really namespaced.
  24. obj = unicode.__new__(cls, name)
  25. else:
  26. obj = unicode.__new__(cls, prefix + ":" + name)
  27. obj.prefix = prefix
  28. obj.name = name
  29. obj.namespace = namespace
  30. return obj
  31. class AttributeValueWithCharsetSubstitution(unicode):
  32. """A stand-in object for a character encoding specified in HTML."""
  33. class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution):
  34. """A generic stand-in for the value of a meta tag's 'charset' attribute.
  35. When Beautiful Soup parses the markup '<meta charset="utf8">', the
  36. value of the 'charset' attribute will be one of these objects.
  37. """
  38. def __new__(cls, original_value):
  39. obj = unicode.__new__(cls, original_value)
  40. obj.original_value = original_value
  41. return obj
  42. def encode(self, encoding):
  43. return encoding
  44. class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution):
  45. """A generic stand-in for the value of a meta tag's 'content' attribute.
  46. When Beautiful Soup parses the markup:
  47. <meta http-equiv="content-type" content="text/html; charset=utf8">
  48. The value of the 'content' attribute will be one of these objects.
  49. """
  50. CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M)
  51. def __new__(cls, original_value):
  52. match = cls.CHARSET_RE.search(original_value)
  53. if match is None:
  54. # No substitution necessary.
  55. return unicode.__new__(unicode, original_value)
  56. obj = unicode.__new__(cls, original_value)
  57. obj.original_value = original_value
  58. return obj
  59. def encode(self, encoding):
  60. def rewrite(match):
  61. return match.group(1) + encoding
  62. return self.CHARSET_RE.sub(rewrite, self.original_value)
  63. class HTMLAwareEntitySubstitution(EntitySubstitution):
  64. """Entity substitution rules that are aware of some HTML quirks.
  65. Specifically, the contents of <script> and <style> tags should not
  66. undergo entity substitution.
  67. Incoming NavigableString objects are checked to see if they're the
  68. direct children of a <script> or <style> tag.
  69. """
  70. cdata_containing_tags = set(["script", "style"])
  71. preformatted_tags = set(["pre"])
  72. @classmethod
  73. def _substitute_if_appropriate(cls, ns, f):
  74. if (isinstance(ns, NavigableString)
  75. and ns.parent is not None
  76. and ns.parent.name in cls.cdata_containing_tags):
  77. # Do nothing.
  78. return ns
  79. # Substitute.
  80. return f(ns)
  81. @classmethod
  82. def substitute_html(cls, ns):
  83. return cls._substitute_if_appropriate(
  84. ns, EntitySubstitution.substitute_html)
  85. @classmethod
  86. def substitute_xml(cls, ns):
  87. return cls._substitute_if_appropriate(
  88. ns, EntitySubstitution.substitute_xml)
  89. class PageElement(object):
  90. """Contains the navigational information for some part of the page
  91. (either a tag or a piece of text)"""
  92. # There are five possible values for the "formatter" argument passed in
  93. # to methods like encode() and prettify():
  94. #
  95. # "html" - All Unicode characters with corresponding HTML entities
  96. # are converted to those entities on output.
  97. # "minimal" - Bare ampersands and angle brackets are converted to
  98. # XML entities: &amp; &lt; &gt;
  99. # None - The null formatter. Unicode characters are never
  100. # converted to entities. This is not recommended, but it's
  101. # faster than "minimal".
  102. # A function - This function will be called on every string that
  103. # needs to undergo entity substitution.
  104. #
  105. # In an HTML document, the default "html" and "minimal" functions
  106. # will leave the contents of <script> and <style> tags alone. For
  107. # an XML document, all tags will be given the same treatment.
  108. HTML_FORMATTERS = {
  109. "html" : HTMLAwareEntitySubstitution.substitute_html,
  110. "minimal" : HTMLAwareEntitySubstitution.substitute_xml,
  111. None : None
  112. }
  113. XML_FORMATTERS = {
  114. "html" : EntitySubstitution.substitute_html,
  115. "minimal" : EntitySubstitution.substitute_xml,
  116. None : None
  117. }
  118. def format_string(self, s, formatter='minimal'):
  119. """Format the given string using the given formatter."""
  120. if not callable(formatter):
  121. formatter = self._formatter_for_name(formatter)
  122. if formatter is None:
  123. output = s
  124. else:
  125. output = formatter(s)
  126. return output
  127. @property
  128. def _is_xml(self):
  129. """Is this element part of an XML tree or an HTML tree?
  130. This is used when mapping a formatter name ("minimal") to an
  131. appropriate function (one that performs entity-substitution on
  132. the contents of <script> and <style> tags, or not). It's
  133. inefficient, but it should be called very rarely.
  134. """
  135. if self.parent is None:
  136. # This is the top-level object. It should have .is_xml set
  137. # from tree creation. If not, take a guess--BS is usually
  138. # used on HTML markup.
  139. return getattr(self, 'is_xml', False)
  140. return self.parent._is_xml
  141. def _formatter_for_name(self, name):
  142. "Look up a formatter function based on its name and the tree."
  143. if self._is_xml:
  144. return self.XML_FORMATTERS.get(
  145. name, EntitySubstitution.substitute_xml)
  146. else:
  147. return self.HTML_FORMATTERS.get(
  148. name, HTMLAwareEntitySubstitution.substitute_xml)
  149. def setup(self, parent=None, previous_element=None):
  150. """Sets up the initial relations between this element and
  151. other elements."""
  152. self.parent = parent
  153. self.previous_element = previous_element
  154. if previous_element is not None:
  155. self.previous_element.next_element = self
  156. self.next_element = None
  157. self.previous_sibling = None
  158. self.next_sibling = None
  159. if self.parent is not None and self.parent.contents:
  160. self.previous_sibling = self.parent.contents[-1]
  161. self.previous_sibling.next_sibling = self
  162. nextSibling = _alias("next_sibling") # BS3
  163. previousSibling = _alias("previous_sibling") # BS3
  164. def replace_with(self, replace_with):
  165. if replace_with is self:
  166. return
  167. if replace_with is self.parent:
  168. raise ValueError("Cannot replace a Tag with its parent.")
  169. old_parent = self.parent
  170. my_index = self.parent.index(self)
  171. self.extract()
  172. old_parent.insert(my_index, replace_with)
  173. return self
  174. replaceWith = replace_with # BS3
  175. def unwrap(self):
  176. my_parent = self.parent
  177. my_index = self.parent.index(self)
  178. self.extract()
  179. for child in reversed(self.contents[:]):
  180. my_parent.insert(my_index, child)
  181. return self
  182. replace_with_children = unwrap
  183. replaceWithChildren = unwrap # BS3
  184. def wrap(self, wrap_inside):
  185. me = self.replace_with(wrap_inside)
  186. wrap_inside.append(me)
  187. return wrap_inside
  188. def extract(self):
  189. """Destructively rips this element out of the tree."""
  190. if self.parent is not None:
  191. del self.parent.contents[self.parent.index(self)]
  192. #Find the two elements that would be next to each other if
  193. #this element (and any children) hadn't been parsed. Connect
  194. #the two.
  195. last_child = self._last_descendant()
  196. next_element = last_child.next_element
  197. if self.previous_element is not None:
  198. self.previous_element.next_element = next_element
  199. if next_element is not None:
  200. next_element.previous_element = self.previous_element
  201. self.previous_element = None
  202. last_child.next_element = None
  203. self.parent = None
  204. if self.previous_sibling is not None:
  205. self.previous_sibling.next_sibling = self.next_sibling
  206. if self.next_sibling is not None:
  207. self.next_sibling.previous_sibling = self.previous_sibling
  208. self.previous_sibling = self.next_sibling = None
  209. return self
  210. def _last_descendant(self, is_initialized=True, accept_self=True):
  211. "Finds the last element beneath this object to be parsed."
  212. if is_initialized and self.next_sibling:
  213. last_child = self.next_sibling.previous_element
  214. else:
  215. last_child = self
  216. while isinstance(last_child, Tag) and last_child.contents:
  217. last_child = last_child.contents[-1]
  218. if not accept_self and last_child == self:
  219. last_child = None
  220. return last_child
  221. # BS3: Not part of the API!
  222. _lastRecursiveChild = _last_descendant
  223. def insert(self, position, new_child):
  224. if new_child is self:
  225. raise ValueError("Cannot insert a tag into itself.")
  226. if (isinstance(new_child, basestring)
  227. and not isinstance(new_child, NavigableString)):
  228. new_child = NavigableString(new_child)
  229. position = min(position, len(self.contents))
  230. if hasattr(new_child, 'parent') and new_child.parent is not None:
  231. # We're 'inserting' an element that's already one
  232. # of this object's children.
  233. if new_child.parent is self:
  234. current_index = self.index(new_child)
  235. if current_index < position:
  236. # We're moving this element further down the list
  237. # of this object's children. That means that when
  238. # we extract this element, our target index will
  239. # jump down one.
  240. position -= 1
  241. new_child.extract()
  242. new_child.parent = self
  243. previous_child = None
  244. if position == 0:
  245. new_child.previous_sibling = None
  246. new_child.previous_element = self
  247. else:
  248. previous_child = self.contents[position - 1]
  249. new_child.previous_sibling = previous_child
  250. new_child.previous_sibling.next_sibling = new_child
  251. new_child.previous_element = previous_child._last_descendant(False)
  252. if new_child.previous_element is not None:
  253. new_child.previous_element.next_element = new_child
  254. new_childs_last_element = new_child._last_descendant(False)
  255. if position >= len(self.contents):
  256. new_child.next_sibling = None
  257. parent = self
  258. parents_next_sibling = None
  259. while parents_next_sibling is None and parent is not None:
  260. parents_next_sibling = parent.next_sibling
  261. parent = parent.parent
  262. if parents_next_sibling is not None:
  263. # We found the element that comes next in the document.
  264. break
  265. if parents_next_sibling is not None:
  266. new_childs_last_element.next_element = parents_next_sibling
  267. else:
  268. # The last element of this tag is the last element in
  269. # the document.
  270. new_childs_last_element.next_element = None
  271. else:
  272. next_child = self.contents[position]
  273. new_child.next_sibling = next_child
  274. if new_child.next_sibling is not None:
  275. new_child.next_sibling.previous_sibling = new_child
  276. new_childs_last_element.next_element = next_child
  277. if new_childs_last_element.next_element is not None:
  278. new_childs_last_element.next_element.previous_element = new_childs_last_element
  279. self.contents.insert(position, new_child)
  280. def append(self, tag):
  281. """Appends the given tag to the contents of this tag."""
  282. self.insert(len(self.contents), tag)
  283. def insert_before(self, predecessor):
  284. """Makes the given element the immediate predecessor of this one.
  285. The two elements will have the same parent, and the given element
  286. will be immediately before this one.
  287. """
  288. if self is predecessor:
  289. raise ValueError("Can't insert an element before itself.")
  290. parent = self.parent
  291. if parent is None:
  292. raise ValueError(
  293. "Element has no parent, so 'before' has no meaning.")
  294. # Extract first so that the index won't be screwed up if they
  295. # are siblings.
  296. if isinstance(predecessor, PageElement):
  297. predecessor.extract()
  298. index = parent.index(self)
  299. parent.insert(index, predecessor)
  300. def insert_after(self, successor):
  301. """Makes the given element the immediate successor of this one.
  302. The two elements will have the same parent, and the given element
  303. will be immediately after this one.
  304. """
  305. if self is successor:
  306. raise ValueError("Can't insert an element after itself.")
  307. parent = self.parent
  308. if parent is None:
  309. raise ValueError(
  310. "Element has no parent, so 'after' has no meaning.")
  311. # Extract first so that the index won't be screwed up if they
  312. # are siblings.
  313. if isinstance(successor, PageElement):
  314. successor.extract()
  315. index = parent.index(self)
  316. parent.insert(index+1, successor)
  317. def find_next(self, name=None, attrs={}, text=None, **kwargs):
  318. """Returns the first item that matches the given criteria and
  319. appears after this Tag in the document."""
  320. return self._find_one(self.find_all_next, name, attrs, text, **kwargs)
  321. findNext = find_next # BS3
  322. def find_all_next(self, name=None, attrs={}, text=None, limit=None,
  323. **kwargs):
  324. """Returns all items that match the given criteria and appear
  325. after this Tag in the document."""
  326. return self._find_all(name, attrs, text, limit, self.next_elements,
  327. **kwargs)
  328. findAllNext = find_all_next # BS3
  329. def find_next_sibling(self, name=None, attrs={}, text=None, **kwargs):
  330. """Returns the closest sibling to this Tag that matches the
  331. given criteria and appears after this Tag in the document."""
  332. return self._find_one(self.find_next_siblings, name, attrs, text,
  333. **kwargs)
  334. findNextSibling = find_next_sibling # BS3
  335. def find_next_siblings(self, name=None, attrs={}, text=None, limit=None,
  336. **kwargs):
  337. """Returns the siblings of this Tag that match the given
  338. criteria and appear after this Tag in the document."""
  339. return self._find_all(name, attrs, text, limit,
  340. self.next_siblings, **kwargs)
  341. findNextSiblings = find_next_siblings # BS3
  342. fetchNextSiblings = find_next_siblings # BS2
  343. def find_previous(self, name=None, attrs={}, text=None, **kwargs):
  344. """Returns the first item that matches the given criteria and
  345. appears before this Tag in the document."""
  346. return self._find_one(
  347. self.find_all_previous, name, attrs, text, **kwargs)
  348. findPrevious = find_previous # BS3
  349. def find_all_previous(self, name=None, attrs={}, text=None, limit=None,
  350. **kwargs):
  351. """Returns all items that match the given criteria and appear
  352. before this Tag in the document."""
  353. return self._find_all(name, attrs, text, limit, self.previous_elements,
  354. **kwargs)
  355. findAllPrevious = find_all_previous # BS3
  356. fetchPrevious = find_all_previous # BS2
  357. def find_previous_sibling(self, name=None, attrs={}, text=None, **kwargs):
  358. """Returns the closest sibling to this Tag that matches the
  359. given criteria and appears before this Tag in the document."""
  360. return self._find_one(self.find_previous_siblings, name, attrs, text,
  361. **kwargs)
  362. findPreviousSibling = find_previous_sibling # BS3
  363. def find_previous_siblings(self, name=None, attrs={}, text=None,
  364. limit=None, **kwargs):
  365. """Returns the siblings of this Tag that match the given
  366. criteria and appear before this Tag in the document."""
  367. return self._find_all(name, attrs, text, limit,
  368. self.previous_siblings, **kwargs)
  369. findPreviousSiblings = find_previous_siblings # BS3
  370. fetchPreviousSiblings = find_previous_siblings # BS2
  371. def find_parent(self, name=None, attrs={}, **kwargs):
  372. """Returns the closest parent of this Tag that matches the given
  373. criteria."""
  374. # NOTE: We can't use _find_one because findParents takes a different
  375. # set of arguments.
  376. r = None
  377. l = self.find_parents(name, attrs, 1, **kwargs)
  378. if l:
  379. r = l[0]
  380. return r
  381. findParent = find_parent # BS3
  382. def find_parents(self, name=None, attrs={}, limit=None, **kwargs):
  383. """Returns the parents of this Tag that match the given
  384. criteria."""
  385. return self._find_all(name, attrs, None, limit, self.parents,
  386. **kwargs)
  387. findParents = find_parents # BS3
  388. fetchParents = find_parents # BS2
  389. @property
  390. def next(self):
  391. return self.next_element
  392. @property
  393. def previous(self):
  394. return self.previous_element
  395. #These methods do the real heavy lifting.
  396. def _find_one(self, method, name, attrs, text, **kwargs):
  397. r = None
  398. l = method(name, attrs, text, 1, **kwargs)
  399. if l:
  400. r = l[0]
  401. return r
  402. def _find_all(self, name, attrs, text, limit, generator, **kwargs):
  403. "Iterates over a generator looking for things that match."
  404. if isinstance(name, SoupStrainer):
  405. strainer = name
  406. else:
  407. strainer = SoupStrainer(name, attrs, text, **kwargs)
  408. if text is None and not limit and not attrs and not kwargs:
  409. if name is True or name is None:
  410. # Optimization to find all tags.
  411. result = (element for element in generator
  412. if isinstance(element, Tag))
  413. return ResultSet(strainer, result)
  414. elif isinstance(name, basestring):
  415. # Optimization to find all tags with a given name.
  416. result = (element for element in generator
  417. if isinstance(element, Tag)
  418. and element.name == name)
  419. return ResultSet(strainer, result)
  420. results = ResultSet(strainer)
  421. while True:
  422. try:
  423. i = next(generator)
  424. except StopIteration:
  425. break
  426. if i:
  427. found = strainer.search(i)
  428. if found:
  429. results.append(found)
  430. if limit and len(results) >= limit:
  431. break
  432. return results
  433. #These generators can be used to navigate starting from both
  434. #NavigableStrings and Tags.
  435. @property
  436. def next_elements(self):
  437. i = self.next_element
  438. while i is not None:
  439. yield i
  440. i = i.next_element
  441. @property
  442. def next_siblings(self):
  443. i = self.next_sibling
  444. while i is not None:
  445. yield i
  446. i = i.next_sibling
  447. @property
  448. def previous_elements(self):
  449. i = self.previous_element
  450. while i is not None:
  451. yield i
  452. i = i.previous_element
  453. @property
  454. def previous_siblings(self):
  455. i = self.previous_sibling
  456. while i is not None:
  457. yield i
  458. i = i.previous_sibling
  459. @property
  460. def parents(self):
  461. i = self.parent
  462. while i is not None:
  463. yield i
  464. i = i.parent
  465. # Methods for supporting CSS selectors.
  466. tag_name_re = re.compile('^[a-z0-9]+$')
  467. # /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  468. # \---/ \---/\-------------/ \-------/
  469. # | | | |
  470. # | | | The value
  471. # | | ~,|,^,$,* or =
  472. # | Attribute
  473. # Tag
  474. attribselect_re = re.compile(
  475. r'^(?P<tag>\w+)?\[(?P<attribute>\w+)(?P<operator>[=~\|\^\$\*]?)' +
  476. r'=?"?(?P<value>[^\]"]*)"?\]$'
  477. )
  478. def _attr_value_as_string(self, value, default=None):
  479. """Force an attribute value into a string representation.
  480. A multi-valued attribute will be converted into a
  481. space-separated stirng.
  482. """
  483. value = self.get(value, default)
  484. if isinstance(value, list) or isinstance(value, tuple):
  485. value =" ".join(value)
  486. return value
  487. def _tag_name_matches_and(self, function, tag_name):
  488. if not tag_name:
  489. return function
  490. else:
  491. def _match(tag):
  492. return tag.name == tag_name and function(tag)
  493. return _match
  494. def _attribute_checker(self, operator, attribute, value=''):
  495. """Create a function that performs a CSS selector operation.
  496. Takes an operator, attribute and optional value. Returns a
  497. function that will return True for elements that match that
  498. combination.
  499. """
  500. if operator == '=':
  501. # string representation of `attribute` is equal to `value`
  502. return lambda el: el._attr_value_as_string(attribute) == value
  503. elif operator == '~':
  504. # space-separated list representation of `attribute`
  505. # contains `value`
  506. def _includes_value(element):
  507. attribute_value = element.get(attribute, [])
  508. if not isinstance(attribute_value, list):
  509. attribute_value = attribute_value.split()
  510. return value in attribute_value
  511. return _includes_value
  512. elif operator == '^':
  513. # string representation of `attribute` starts with `value`
  514. return lambda el: el._attr_value_as_string(
  515. attribute, '').startswith(value)
  516. elif operator == '$':
  517. # string represenation of `attribute` ends with `value`
  518. return lambda el: el._attr_value_as_string(
  519. attribute, '').endswith(value)
  520. elif operator == '*':
  521. # string representation of `attribute` contains `value`
  522. return lambda el: value in el._attr_value_as_string(attribute, '')
  523. elif operator == '|':
  524. # string representation of `attribute` is either exactly
  525. # `value` or starts with `value` and then a dash.
  526. def _is_or_starts_with_dash(element):
  527. attribute_value = element._attr_value_as_string(attribute, '')
  528. return (attribute_value == value or attribute_value.startswith(
  529. value + '-'))
  530. return _is_or_starts_with_dash
  531. else:
  532. return lambda el: el.has_attr(attribute)
  533. # Old non-property versions of the generators, for backwards
  534. # compatibility with BS3.
  535. def nextGenerator(self):
  536. return self.next_elements
  537. def nextSiblingGenerator(self):
  538. return self.next_siblings
  539. def previousGenerator(self):
  540. return self.previous_elements
  541. def previousSiblingGenerator(self):
  542. return self.previous_siblings
  543. def parentGenerator(self):
  544. return self.parents
  545. class NavigableString(unicode, PageElement):
  546. PREFIX = ''
  547. SUFFIX = ''
  548. def __new__(cls, value):
  549. """Create a new NavigableString.
  550. When unpickling a NavigableString, this method is called with
  551. the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
  552. passed in to the superclass's __new__ or the superclass won't know
  553. how to handle non-ASCII characters.
  554. """
  555. if isinstance(value, unicode):
  556. return unicode.__new__(cls, value)
  557. return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
  558. def __copy__(self):
  559. return self
  560. def __getnewargs__(self):
  561. return (unicode(self),)
  562. def __getattr__(self, attr):
  563. """text.string gives you text. This is for backwards
  564. compatibility for Navigable*String, but for CData* it lets you
  565. get the string without the CData wrapper."""
  566. if attr == 'string':
  567. return self
  568. else:
  569. raise AttributeError(
  570. "'%s' object has no attribute '%s'" % (
  571. self.__class__.__name__, attr))
  572. def output_ready(self, formatter="minimal"):
  573. output = self.format_string(self, formatter)
  574. return self.PREFIX + output + self.SUFFIX
  575. @property
  576. def name(self):
  577. return None
  578. @name.setter
  579. def name(self, name):
  580. raise AttributeError("A NavigableString cannot be given a name.")
  581. class PreformattedString(NavigableString):
  582. """A NavigableString not subject to the normal formatting rules.
  583. The string will be passed into the formatter (to trigger side effects),
  584. but the return value will be ignored.
  585. """
  586. def output_ready(self, formatter="minimal"):
  587. """CData strings are passed into the formatter.
  588. But the return value is ignored."""
  589. self.format_string(self, formatter)
  590. return self.PREFIX + self + self.SUFFIX
  591. class CData(PreformattedString):
  592. PREFIX = u'<![CDATA['
  593. SUFFIX = u']]>'
  594. class ProcessingInstruction(PreformattedString):
  595. PREFIX = u'<?'
  596. SUFFIX = u'?>'
  597. class Comment(PreformattedString):
  598. PREFIX = u'<!--'
  599. SUFFIX = u'-->'
  600. class Declaration(PreformattedString):
  601. PREFIX = u'<!'
  602. SUFFIX = u'!>'
  603. class Doctype(PreformattedString):
  604. @classmethod
  605. def for_name_and_ids(cls, name, pub_id, system_id):
  606. value = name or ''
  607. if pub_id is not None:
  608. value += ' PUBLIC "%s"' % pub_id
  609. if system_id is not None:
  610. value += ' "%s"' % system_id
  611. elif system_id is not None:
  612. value += ' SYSTEM "%s"' % system_id
  613. return Doctype(value)
  614. PREFIX = u'<!DOCTYPE '
  615. SUFFIX = u'>\n'
  616. class Tag(PageElement):
  617. """Represents a found HTML tag with its attributes and contents."""
  618. def __init__(self, parser=None, builder=None, name=None, namespace=None,
  619. prefix=None, attrs=None, parent=None, previous=None):
  620. "Basic constructor."
  621. if parser is None:
  622. self.parser_class = None
  623. else:
  624. # We don't actually store the parser object: that lets extracted
  625. # chunks be garbage-collected.
  626. self.parser_class = parser.__class__
  627. if name is None:
  628. raise ValueError("No value provided for new tag's name.")
  629. self.name = name
  630. self.namespace = namespace
  631. self.prefix = prefix
  632. if attrs is None:
  633. attrs = {}
  634. elif attrs and builder.cdata_list_attributes:
  635. attrs = builder._replace_cdata_list_attribute_values(
  636. self.name, attrs)
  637. else:
  638. attrs = dict(attrs)
  639. self.attrs = attrs
  640. self.contents = []
  641. self.setup(parent, previous)
  642. self.hidden = False
  643. # Set up any substitutions, such as the charset in a META tag.
  644. if builder is not None:
  645. builder.set_up_substitutions(self)
  646. self.can_be_empty_element = builder.can_be_empty_element(name)
  647. else:
  648. self.can_be_empty_element = False
  649. parserClass = _alias("parser_class") # BS3
  650. @property
  651. def is_empty_element(self):
  652. """Is this tag an empty-element tag? (aka a self-closing tag)
  653. A tag that has contents is never an empty-element tag.
  654. A tag that has no contents may or may not be an empty-element
  655. tag. It depends on the builder used to create the tag. If the
  656. builder has a designated list of empty-element tags, then only
  657. a tag whose name shows up in that list is considered an
  658. empty-element tag.
  659. If the builder has no designated list of empty-element tags,
  660. then any tag with no contents is an empty-element tag.
  661. """
  662. return len(self.contents) == 0 and self.can_be_empty_element
  663. isSelfClosing = is_empty_element # BS3
  664. @property
  665. def string(self):
  666. """Convenience property to get the single string within this tag.
  667. :Return: If this tag has a single string child, return value
  668. is that string. If this tag has no children, or more than one
  669. child, return value is None. If this tag has one child tag,
  670. return value is the 'string' attribute of the child tag,
  671. recursively.
  672. """
  673. if len(self.contents) != 1:
  674. return None
  675. child = self.contents[0]
  676. if isinstance(child, NavigableString):
  677. return child
  678. return child.string
  679. @string.setter
  680. def string(self, string):
  681. self.clear()
  682. self.append(string.__class__(string))
  683. def _all_strings(self, strip=False, types=(NavigableString, CData)):
  684. """Yield all strings of certain classes, possibly stripping them.
  685. By default, yields only NavigableString and CData objects. So
  686. no comments, processing instructions, etc.
  687. """
  688. for descendant in self.descendants:
  689. if (
  690. (types is None and not isinstance(descendant, NavigableString))
  691. or
  692. (types is not None and type(descendant) not in types)):
  693. continue
  694. if strip:
  695. descendant = descendant.strip()
  696. if len(descendant) == 0:
  697. continue
  698. yield descendant
  699. strings = property(_all_strings)
  700. @property
  701. def stripped_strings(self):
  702. for string in self._all_strings(True):
  703. yield string
  704. def get_text(self, separator=u"", strip=False,
  705. types=(NavigableString, CData)):
  706. """
  707. Get all child strings, concatenated using the given separator.
  708. """
  709. return separator.join([s for s in self._all_strings(
  710. strip, types=types)])
  711. getText = get_text
  712. text = property(get_text)
  713. def decompose(self):
  714. """Recursively destroys the contents of this tree."""
  715. self.extract()
  716. i = self
  717. while i is not None:
  718. next = i.next_element
  719. i.__dict__.clear()
  720. i.contents = []
  721. i = next
  722. def clear(self, decompose=False):
  723. """
  724. Extract all children. If decompose is True, decompose instead.
  725. """
  726. if decompose:
  727. for element in self.contents[:]:
  728. if isinstance(element, Tag):
  729. element.decompose()
  730. else:
  731. element.extract()
  732. else:
  733. for element in self.contents[:]:
  734. element.extract()
  735. def index(self, element):
  736. """
  737. Find the index of a child by identity, not value. Avoids issues with
  738. tag.contents.index(element) getting the index of equal elements.
  739. """
  740. for i, child in enumerate(self.contents):
  741. if child is element:
  742. return i
  743. raise ValueError("Tag.index: element not in tag")
  744. def get(self, key, default=None):
  745. """Returns the value of the 'key' attribute for the tag, or
  746. the value given for 'default' if it doesn't have that
  747. attribute."""
  748. return self.attrs.get(key, default)
  749. def has_attr(self, key):
  750. return key in self.attrs
  751. def __hash__(self):
  752. return str(self).__hash__()
  753. def __getitem__(self, key):
  754. """tag[key] returns the value of the 'key' attribute for the tag,
  755. and throws an exception if it's not there."""
  756. return self.attrs[key]
  757. def __iter__(self):
  758. "Iterating over a tag iterates over its contents."
  759. return iter(self.contents)
  760. def __len__(self):
  761. "The length of a tag is the length of its list of contents."
  762. return len(self.contents)
  763. def __contains__(self, x):
  764. return x in self.contents
  765. def __nonzero__(self):
  766. "A tag is non-None even if it has no contents."
  767. return True
  768. def __setitem__(self, key, value):
  769. """Setting tag[key] sets the value of the 'key' attribute for the
  770. tag."""
  771. self.attrs[key] = value
  772. def __delitem__(self, key):
  773. "Deleting tag[key] deletes all 'key' attributes for the tag."
  774. self.attrs.pop(key, None)
  775. def __call__(self, *args, **kwargs):
  776. """Calling a tag like a function is the same as calling its
  777. find_all() method. Eg. tag('a') returns a list of all the A tags
  778. found within this tag."""
  779. return self.find_all(*args, **kwargs)
  780. def __getattr__(self, tag):
  781. #print "Getattr %s.%s" % (self.__class__, tag)
  782. if len(tag) > 3 and tag.endswith('Tag'):
  783. # BS3: soup.aTag -> "soup.find("a")
  784. tag_name = tag[:-3]
  785. warnings.warn(
  786. '.%sTag is deprecated, use .find("%s") instead.' % (
  787. tag_name, tag_name))
  788. return self.find(tag_name)
  789. # We special case contents to avoid recursion.
  790. elif not tag.startswith("__") and not tag=="contents":
  791. return self.find(tag)
  792. raise AttributeError(
  793. "'%s' object has no attribute '%s'" % (self.__class__, tag))
  794. def __eq__(self, other):
  795. """Returns true iff this tag has the same name, the same attributes,
  796. and the same contents (recursively) as the given tag."""
  797. if self is other:
  798. return True
  799. if (not hasattr(other, 'name') or
  800. not hasattr(other, 'attrs') or
  801. not hasattr(other, 'contents') or
  802. self.name != other.name or
  803. self.attrs != other.attrs or
  804. len(self) != len(other)):
  805. return False
  806. for i, my_child in enumerate(self.contents):
  807. if my_child != other.contents[i]:
  808. return False
  809. return True
  810. def __ne__(self, other):
  811. """Returns true iff this tag is not identical to the other tag,
  812. as defined in __eq__."""
  813. return not self == other
  814. def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  815. """Renders this tag as a string."""
  816. return self.encode(encoding)
  817. def __unicode__(self):
  818. return self.decode()
  819. def __str__(self):
  820. return self.encode()
  821. if PY3K:
  822. __str__ = __repr__ = __unicode__
  823. def encode(self, encoding=DEFAULT_OUTPUT_ENCODING,
  824. indent_level=None, formatter="minimal",
  825. errors="xmlcharrefreplace"):
  826. # Turn the data structure into Unicode, then encode the
  827. # Unicode.
  828. u = self.decode(indent_level, encoding, formatter)
  829. return u.encode(encoding, errors)
  830. def _should_pretty_print(self, indent_level):
  831. """Should this tag be pretty-printed?"""
  832. return (
  833. indent_level is not None and
  834. (self.name not in HTMLAwareEntitySubstitution.preformatted_tags
  835. or self._is_xml))
  836. def decode(self, indent_level=None,
  837. eventual_encoding=DEFAULT_OUTPUT_ENCODING,
  838. formatter="minimal"):
  839. """Returns a Unicode representation of this tag and its contents.
  840. :param eventual_encoding: The tag is destined to be
  841. encoded into this encoding. This method is _not_
  842. responsible for performing that encoding. This information
  843. is passed in so that it can be substituted in if the
  844. document contains a <META> tag that mentions the document's
  845. encoding.
  846. """
  847. # First off, turn a string formatter into a function. This
  848. # will stop the lookup from happening over and over again.
  849. if not callable(formatter):
  850. formatter = self._formatter_for_name(formatter)
  851. attrs = []
  852. if self.attrs:
  853. for key, val in sorted(self.attrs.items()):
  854. if val is None:
  855. decoded = key
  856. else:
  857. if isinstance(val, list) or isinstance(val, tuple):
  858. val = ' '.join(val)
  859. elif not isinstance(val, basestring):
  860. val = unicode(val)
  861. elif (
  862. isinstance(val, AttributeValueWithCharsetSubstitution)
  863. and eventual_encoding is not None):
  864. val = val.encode(eventual_encoding)
  865. text = self.format_string(val, formatter)
  866. decoded = (
  867. unicode(key) + '='
  868. + EntitySubstitution.quoted_attribute_value(text))
  869. attrs.append(decoded)
  870. close = ''
  871. closeTag = ''
  872. prefix = ''
  873. if self.prefix:
  874. prefix = self.prefix + ":"
  875. if self.is_empty_element:
  876. close = '/'
  877. else:
  878. closeTag = '</%s%s>' % (prefix, self.name)
  879. pretty_print = self._should_pretty_print(indent_level)
  880. space = ''
  881. indent_space = ''
  882. if indent_level is not None:
  883. indent_space = (' ' * (indent_level - 1))
  884. if pretty_print:
  885. space = indent_space
  886. indent_contents = indent_level + 1
  887. else:
  888. indent_contents = None
  889. contents = self.decode_contents(
  890. indent_contents, eventual_encoding, formatter)
  891. if self.hidden:
  892. # This is the 'document root' object.
  893. s = contents
  894. else:
  895. s = []
  896. attribute_string = ''
  897. if attrs:
  898. attribute_string = ' ' + ' '.join(attrs)
  899. if indent_level is not None:
  900. # Even if this particular tag is not pretty-printed,
  901. # we should indent up to the start of the tag.
  902. s.append(indent_space)
  903. s.append('<%s%s%s%s>' % (
  904. prefix, self.name, attribute_string, close))
  905. if pretty_print:
  906. s.append("\n")
  907. s.append(contents)
  908. if pretty_print and contents and contents[-1] != "\n":
  909. s.append("\n")
  910. if pretty_print and closeTag:
  911. s.append(space)
  912. s.append(closeTag)
  913. if indent_level is not None and closeTag and self.next_sibling:
  914. # Even if this particular tag is not pretty-printed,
  915. # we're now done with the tag, and we should add a
  916. # newline if appropriate.
  917. s.append("\n")
  918. s = ''.join(s)
  919. return s
  920. def prettify(self, encoding=None, formatter="minimal"):
  921. if encoding is None:
  922. return self.decode(True, formatter=formatter)
  923. else:
  924. return self.encode(encoding, True, formatter=formatter)
  925. def decode_contents(self, indent_level=None,
  926. eventual_encoding=DEFAULT_OUTPUT_ENCODING,
  927. formatter="minimal"):
  928. """Renders the contents of this tag as a Unicode string.
  929. :param eventual_encoding: The tag is destined to be
  930. encoded into this encoding. This method is _not_
  931. responsible for performing that encoding. This information
  932. is passed in so that it can be substituted in if the
  933. document contains a <META> tag that mentions the document's
  934. encoding.
  935. """
  936. # First off, turn a string formatter into a function. This
  937. # will stop the lookup from happening over and over again.
  938. if not callable(formatter):
  939. formatter = self._formatter_for_name(formatter)
  940. pretty_print = (indent_level is not None)
  941. s = []
  942. for c in self:
  943. text = None
  944. if isinstance(c, NavigableString):
  945. text = c.output_ready(formatter)
  946. elif isinstance(c, Tag):
  947. s.append(c.decode(indent_level, eventual_encoding,
  948. formatter))
  949. if text and indent_level and not self.name == 'pre':
  950. text = text.strip()
  951. if text:
  952. if pretty_print and not self.name == 'pre':
  953. s.append(" " * (indent_level - 1))
  954. s.append(text)
  955. if pretty_print and not self.name == 'pre':
  956. s.append("\n")
  957. return ''.join(s)
  958. def encode_contents(
  959. self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING,
  960. formatter="minimal"):
  961. """Renders the contents of this tag as a bytestring."""
  962. contents = self.decode_contents(indent_level, encoding, formatter)
  963. return contents.encode(encoding)
  964. # Old method for BS3 compatibility
  965. def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
  966. prettyPrint=False, indentLevel=0):
  967. if not prettyPrint:
  968. indentLevel = None
  969. return self.encode_contents(
  970. indent_level=indentLevel, encoding=encoding)
  971. #Soup methods
  972. def find(self, name=None, attrs={}, recursive=True, text=None,
  973. **kwargs):
  974. """Return only the first child of this Tag matching the given
  975. criteria."""
  976. r = None
  977. l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
  978. if l:
  979. r = l[0]
  980. return r
  981. findChild = find
  982. def find_all(self, name=None, attrs={}, recursive=True, text=None,
  983. limit=None, **kwargs):
  984. """Extracts a list of Tag objects that match the given
  985. criteria. You can specify the name of the Tag and any
  986. attributes you want the Tag to have.
  987. The value of a key-value pair in the 'attrs' map can be a
  988. string, a list of strings, a regular expression object, or a
  989. callable that takes a string and returns whether or not the
  990. string matches for some custom definition of 'matches'. The
  991. same is true of the tag name."""
  992. generator = self.descendants
  993. if not recursive:
  994. generator = self.children
  995. return self._find_all(name, attrs, text, limit, generator, **kwargs)
  996. findAll = find_all # BS3
  997. findChildren = find_all # BS2
  998. #Generator methods
  999. @property
  1000. def children(self):
  1001. # return iter() to make the purpose of the method clear
  1002. return iter(self.contents) # XXX This seems to be untested.
  1003. @property
  1004. def descendants(self):
  1005. if not len(self.contents):
  1006. return
  1007. stopNode = self._last_descendant().next_element
  1008. current = self.contents[0]
  1009. while current is not stopNode:
  1010. yield current
  1011. current = current.next_element
  1012. # CSS selector code
  1013. _selector_combinators = ['>', '+', '~']
  1014. _select_debug = False
  1015. def select(self, selector, _candidate_generator=None):
  1016. """Perform a CSS selection operation on the current element."""
  1017. tokens = selector.split()
  1018. current_context = [self]
  1019. if tokens[-1] in self._selector_combinators:
  1020. raise ValueError(
  1021. 'Final combinator "%s" is missing an argument.' % tokens[-1])
  1022. if self._select_debug:
  1023. print 'Running CSS selector "%s"' % selector
  1024. for index, token in enumerate(tokens):
  1025. if self._select_debug:
  1026. print ' Considering token "%s"' % token
  1027. recursive_candidate_generator = None
  1028. tag_name = None
  1029. if tokens[index-1] in self._selector_combinators:
  1030. # This token was consumed by the previous combinator. Skip it.
  1031. if self._select_debug:
  1032. print ' Token was consumed by the previous combinator.'
  1033. continue
  1034. # Each operation corresponds to a checker function, a rule
  1035. # for determining whether a candidate matches the
  1036. # selector. Candidates are generated by the active
  1037. # iterator.
  1038. checker = None
  1039. m = self.attribselect_re.match(token)
  1040. if m is not None:
  1041. # Attribute selector
  1042. tag_name, attribute, operator, value = m.groups()
  1043. checker = self._attribute_checker(operator, attribute, value)
  1044. elif '#' in token:
  1045. # ID selector
  1046. tag_name, tag_id = token.split('#', 1)
  1047. def id_matches(tag):
  1048. return tag.get('id', None) == tag_id
  1049. checker = id_matches
  1050. elif '.' in token:
  1051. # Class selector
  1052. tag_name, klass = token.split('.', 1)
  1053. classes = set(klass.split('.'))
  1054. def classes_match(candidate):
  1055. return classes.issubset(candidate.get('class', []))
  1056. checker = classes_match
  1057. elif ':' in token:
  1058. # Pseudo-class
  1059. tag_name, pseudo = token.split(':', 1)
  1060. if tag_name == '':
  1061. raise ValueError(
  1062. "A pseudo-class must be prefixed with a tag name.")
  1063. pseudo_attributes = re.match('([a-zA-Z\d-]+)\(([a-zA-Z\d]+)\)', pseudo)
  1064. found = []
  1065. if pseudo_attributes is not None:
  1066. pseudo_type, pseudo_value = pseudo_attributes.groups()
  1067. if pseudo_type == 'nth-of-type':
  1068. try:
  1069. pseudo_value = int(pseudo_value)
  1070. except:
  1071. raise NotImplementedError(
  1072. 'Only numeric values are currently supported for the nth-of-type pseudo-class.')
  1073. if pseudo_value < 1:
  1074. raise ValueError(
  1075. 'nth-of-type pseudo-class value must be at least 1.')
  1076. class Counter(object):
  1077. def __init__(self, destination):
  1078. self.count = 0
  1079. self.destination = destination
  1080. def nth_child_of_type(self, tag):
  1081. self.count += 1
  1082. if self.count == self.destination:
  1083. return True
  1084. if self.count > self.destination:
  1085. # Stop the generator that's sending us
  1086. # these things.
  1087. raise StopIteration()
  1088. return False
  1089. checker = Counter(pseudo_value).nth_child_of_type
  1090. else:
  1091. raise NotImplementedError(
  1092. 'Only the following pseudo-classes are implemented: nth-of-type.')
  1093. elif token == '*':
  1094. # Star selector -- matches everything
  1095. pass
  1096. elif token == '>':
  1097. # Run the next token as a CSS selector against the
  1098. # direct children of each tag in the current context.
  1099. recursive_candidate_generator = lambda tag: tag.children
  1100. elif token == '~':
  1101. # Run the next token as a CSS selector against the
  1102. # siblings of each tag in the current context.
  1103. recursive_candidate_generator = lambda tag: tag.next_siblings
  1104. elif token == '+':
  1105. # For each tag in the current context, run the next
  1106. # token as a CSS selector against the tag's next
  1107. # sibling that's a tag.
  1108. def next_tag_sibling(tag):
  1109. yield tag.find_next_sibling(True)
  1110. recursive_candidate_generator = next_tag_sibling
  1111. elif self.tag_name_re.match(token):
  1112. # Just a tag name.
  1113. tag_name = token
  1114. else:
  1115. raise ValueError(
  1116. 'Unsupported or invalid CSS selector: "%s"' % token)
  1117. if recursive_candidate_generator:
  1118. # This happens when the selector looks like "> foo".
  1119. #
  1120. # The generator calls select() recursively on every
  1121. # member of the current context, passing in a different
  1122. # candidate generator and a different selector.
  1123. #
  1124. # In the case of "> foo", the candidate generator is
  1125. # one that yields a tag's direct children (">"), and
  1126. # the selector is "foo".
  1127. next_token = tokens[index+1]
  1128. def recursive_select(tag):
  1129. if self._select_debug:
  1130. print ' Calling select("%s") recursively on %s %s' % (next_token, tag.name, tag.attrs)
  1131. print '-' * 40
  1132. for i in tag.select(next_token, recursive_candidate_generator):
  1133. if self._select_debug:
  1134. print '(Recursive select picked up candidate %s %s)' % (i.name, i.attrs)
  1135. yield i