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

/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py

https://bitbucket.org/codefirex/external_webkit
Python | 2000 lines | 1789 code | 82 blank | 129 comment | 132 complexity | 1433407a87b3e41809a32d9e1220bd7f MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. """Beautiful Soup
  2. Elixir and Tonic
  3. "The Screen-Scraper's Friend"
  4. http://www.crummy.com/software/BeautifulSoup/
  5. Beautiful Soup parses a (possibly invalid) XML or HTML document into a
  6. tree representation. It provides methods and Pythonic idioms that make
  7. it easy to navigate, search, and modify the tree.
  8. A well-formed XML/HTML document yields a well-formed data
  9. structure. An ill-formed XML/HTML document yields a correspondingly
  10. ill-formed data structure. If your document is only locally
  11. well-formed, you can use this library to find and process the
  12. well-formed part of it.
  13. Beautiful Soup works with Python 2.2 and up. It has no external
  14. dependencies, but you'll have more success at converting data to UTF-8
  15. if you also install these three packages:
  16. * chardet, for auto-detecting character encodings
  17. http://chardet.feedparser.org/
  18. * cjkcodecs and iconv_codec, which add more encodings to the ones supported
  19. by stock Python.
  20. http://cjkpython.i18n.org/
  21. Beautiful Soup defines classes for two main parsing strategies:
  22. * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific
  23. language that kind of looks like XML.
  24. * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid
  25. or invalid. This class has web browser-like heuristics for
  26. obtaining a sensible parse tree in the face of common HTML errors.
  27. Beautiful Soup also defines a class (UnicodeDammit) for autodetecting
  28. the encoding of an HTML or XML document, and converting it to
  29. Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser.
  30. For more than you ever wanted to know about Beautiful Soup, see the
  31. documentation:
  32. http://www.crummy.com/software/BeautifulSoup/documentation.html
  33. Here, have some legalese:
  34. Copyright (c) 2004-2009, Leonard Richardson
  35. All rights reserved.
  36. Redistribution and use in source and binary forms, with or without
  37. modification, are permitted provided that the following conditions are
  38. met:
  39. * Redistributions of source code must retain the above copyright
  40. notice, this list of conditions and the following disclaimer.
  41. * Redistributions in binary form must reproduce the above
  42. copyright notice, this list of conditions and the following
  43. disclaimer in the documentation and/or other materials provided
  44. with the distribution.
  45. * Neither the name of the the Beautiful Soup Consortium and All
  46. Night Kosher Bakery nor the names of its contributors may be
  47. used to endorse or promote products derived from this software
  48. without specific prior written permission.
  49. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  50. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  51. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  52. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  53. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  54. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  55. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  56. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  57. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  58. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  59. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT.
  60. """
  61. from __future__ import generators
  62. __author__ = "Leonard Richardson (leonardr@segfault.org)"
  63. __version__ = "3.1.0.1"
  64. __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson"
  65. __license__ = "New-style BSD"
  66. import codecs
  67. import markupbase
  68. import types
  69. import re
  70. from HTMLParser import HTMLParser, HTMLParseError
  71. try:
  72. from htmlentitydefs import name2codepoint
  73. except ImportError:
  74. name2codepoint = {}
  75. try:
  76. set
  77. except NameError:
  78. from sets import Set as set
  79. #These hacks make Beautiful Soup able to parse XML with namespaces
  80. markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match
  81. DEFAULT_OUTPUT_ENCODING = "utf-8"
  82. # First, the classes that represent markup elements.
  83. def sob(unicode, encoding):
  84. """Returns either the given Unicode string or its encoding."""
  85. if encoding is None:
  86. return unicode
  87. else:
  88. return unicode.encode(encoding)
  89. class PageElement:
  90. """Contains the navigational information for some part of the page
  91. (either a tag or a piece of text)"""
  92. def setup(self, parent=None, previous=None):
  93. """Sets up the initial relations between this element and
  94. other elements."""
  95. self.parent = parent
  96. self.previous = previous
  97. self.next = None
  98. self.previousSibling = None
  99. self.nextSibling = None
  100. if self.parent and self.parent.contents:
  101. self.previousSibling = self.parent.contents[-1]
  102. self.previousSibling.nextSibling = self
  103. def replaceWith(self, replaceWith):
  104. oldParent = self.parent
  105. myIndex = self.parent.contents.index(self)
  106. if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent:
  107. # We're replacing this element with one of its siblings.
  108. index = self.parent.contents.index(replaceWith)
  109. if index and index < myIndex:
  110. # Furthermore, it comes before this element. That
  111. # means that when we extract it, the index of this
  112. # element will change.
  113. myIndex = myIndex - 1
  114. self.extract()
  115. oldParent.insert(myIndex, replaceWith)
  116. def extract(self):
  117. """Destructively rips this element out of the tree."""
  118. if self.parent:
  119. try:
  120. self.parent.contents.remove(self)
  121. except ValueError:
  122. pass
  123. #Find the two elements that would be next to each other if
  124. #this element (and any children) hadn't been parsed. Connect
  125. #the two.
  126. lastChild = self._lastRecursiveChild()
  127. nextElement = lastChild.next
  128. if self.previous:
  129. self.previous.next = nextElement
  130. if nextElement:
  131. nextElement.previous = self.previous
  132. self.previous = None
  133. lastChild.next = None
  134. self.parent = None
  135. if self.previousSibling:
  136. self.previousSibling.nextSibling = self.nextSibling
  137. if self.nextSibling:
  138. self.nextSibling.previousSibling = self.previousSibling
  139. self.previousSibling = self.nextSibling = None
  140. return self
  141. def _lastRecursiveChild(self):
  142. "Finds the last element beneath this object to be parsed."
  143. lastChild = self
  144. while hasattr(lastChild, 'contents') and lastChild.contents:
  145. lastChild = lastChild.contents[-1]
  146. return lastChild
  147. def insert(self, position, newChild):
  148. if (isinstance(newChild, basestring)
  149. or isinstance(newChild, unicode)) \
  150. and not isinstance(newChild, NavigableString):
  151. newChild = NavigableString(newChild)
  152. position = min(position, len(self.contents))
  153. if hasattr(newChild, 'parent') and newChild.parent != None:
  154. # We're 'inserting' an element that's already one
  155. # of this object's children.
  156. if newChild.parent == self:
  157. index = self.find(newChild)
  158. if index and index < position:
  159. # Furthermore we're moving it further down the
  160. # list of this object's children. That means that
  161. # when we extract this element, our target index
  162. # will jump down one.
  163. position = position - 1
  164. newChild.extract()
  165. newChild.parent = self
  166. previousChild = None
  167. if position == 0:
  168. newChild.previousSibling = None
  169. newChild.previous = self
  170. else:
  171. previousChild = self.contents[position-1]
  172. newChild.previousSibling = previousChild
  173. newChild.previousSibling.nextSibling = newChild
  174. newChild.previous = previousChild._lastRecursiveChild()
  175. if newChild.previous:
  176. newChild.previous.next = newChild
  177. newChildsLastElement = newChild._lastRecursiveChild()
  178. if position >= len(self.contents):
  179. newChild.nextSibling = None
  180. parent = self
  181. parentsNextSibling = None
  182. while not parentsNextSibling:
  183. parentsNextSibling = parent.nextSibling
  184. parent = parent.parent
  185. if not parent: # This is the last element in the document.
  186. break
  187. if parentsNextSibling:
  188. newChildsLastElement.next = parentsNextSibling
  189. else:
  190. newChildsLastElement.next = None
  191. else:
  192. nextChild = self.contents[position]
  193. newChild.nextSibling = nextChild
  194. if newChild.nextSibling:
  195. newChild.nextSibling.previousSibling = newChild
  196. newChildsLastElement.next = nextChild
  197. if newChildsLastElement.next:
  198. newChildsLastElement.next.previous = newChildsLastElement
  199. self.contents.insert(position, newChild)
  200. def append(self, tag):
  201. """Appends the given tag to the contents of this tag."""
  202. self.insert(len(self.contents), tag)
  203. def findNext(self, name=None, attrs={}, text=None, **kwargs):
  204. """Returns the first item that matches the given criteria and
  205. appears after this Tag in the document."""
  206. return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
  207. def findAllNext(self, name=None, attrs={}, text=None, limit=None,
  208. **kwargs):
  209. """Returns all items that match the given criteria and appear
  210. after this Tag in the document."""
  211. return self._findAll(name, attrs, text, limit, self.nextGenerator,
  212. **kwargs)
  213. def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
  214. """Returns the closest sibling to this Tag that matches the
  215. given criteria and appears after this Tag in the document."""
  216. return self._findOne(self.findNextSiblings, name, attrs, text,
  217. **kwargs)
  218. def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,
  219. **kwargs):
  220. """Returns the siblings of this Tag that match the given
  221. criteria and appear after this Tag in the document."""
  222. return self._findAll(name, attrs, text, limit,
  223. self.nextSiblingGenerator, **kwargs)
  224. fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x
  225. def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
  226. """Returns the first item that matches the given criteria and
  227. appears before this Tag in the document."""
  228. return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
  229. def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,
  230. **kwargs):
  231. """Returns all items that match the given criteria and appear
  232. before this Tag in the document."""
  233. return self._findAll(name, attrs, text, limit, self.previousGenerator,
  234. **kwargs)
  235. fetchPrevious = findAllPrevious # Compatibility with pre-3.x
  236. def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
  237. """Returns the closest sibling to this Tag that matches the
  238. given criteria and appears before this Tag in the document."""
  239. return self._findOne(self.findPreviousSiblings, name, attrs, text,
  240. **kwargs)
  241. def findPreviousSiblings(self, name=None, attrs={}, text=None,
  242. limit=None, **kwargs):
  243. """Returns the siblings of this Tag that match the given
  244. criteria and appear before this Tag in the document."""
  245. return self._findAll(name, attrs, text, limit,
  246. self.previousSiblingGenerator, **kwargs)
  247. fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x
  248. def findParent(self, name=None, attrs={}, **kwargs):
  249. """Returns the closest parent of this Tag that matches the given
  250. criteria."""
  251. # NOTE: We can't use _findOne because findParents takes a different
  252. # set of arguments.
  253. r = None
  254. l = self.findParents(name, attrs, 1)
  255. if l:
  256. r = l[0]
  257. return r
  258. def findParents(self, name=None, attrs={}, limit=None, **kwargs):
  259. """Returns the parents of this Tag that match the given
  260. criteria."""
  261. return self._findAll(name, attrs, None, limit, self.parentGenerator,
  262. **kwargs)
  263. fetchParents = findParents # Compatibility with pre-3.x
  264. #These methods do the real heavy lifting.
  265. def _findOne(self, method, name, attrs, text, **kwargs):
  266. r = None
  267. l = method(name, attrs, text, 1, **kwargs)
  268. if l:
  269. r = l[0]
  270. return r
  271. def _findAll(self, name, attrs, text, limit, generator, **kwargs):
  272. "Iterates over a generator looking for things that match."
  273. if isinstance(name, SoupStrainer):
  274. strainer = name
  275. else:
  276. # Build a SoupStrainer
  277. strainer = SoupStrainer(name, attrs, text, **kwargs)
  278. results = ResultSet(strainer)
  279. g = generator()
  280. while True:
  281. try:
  282. i = g.next()
  283. except StopIteration:
  284. break
  285. if i:
  286. found = strainer.search(i)
  287. if found:
  288. results.append(found)
  289. if limit and len(results) >= limit:
  290. break
  291. return results
  292. #These Generators can be used to navigate starting from both
  293. #NavigableStrings and Tags.
  294. def nextGenerator(self):
  295. i = self
  296. while i:
  297. i = i.next
  298. yield i
  299. def nextSiblingGenerator(self):
  300. i = self
  301. while i:
  302. i = i.nextSibling
  303. yield i
  304. def previousGenerator(self):
  305. i = self
  306. while i:
  307. i = i.previous
  308. yield i
  309. def previousSiblingGenerator(self):
  310. i = self
  311. while i:
  312. i = i.previousSibling
  313. yield i
  314. def parentGenerator(self):
  315. i = self
  316. while i:
  317. i = i.parent
  318. yield i
  319. # Utility methods
  320. def substituteEncoding(self, str, encoding=None):
  321. encoding = encoding or "utf-8"
  322. return str.replace("%SOUP-ENCODING%", encoding)
  323. def toEncoding(self, s, encoding=None):
  324. """Encodes an object to a string in some encoding, or to Unicode.
  325. ."""
  326. if isinstance(s, unicode):
  327. if encoding:
  328. s = s.encode(encoding)
  329. elif isinstance(s, str):
  330. if encoding:
  331. s = s.encode(encoding)
  332. else:
  333. s = unicode(s)
  334. else:
  335. if encoding:
  336. s = self.toEncoding(str(s), encoding)
  337. else:
  338. s = unicode(s)
  339. return s
  340. class NavigableString(unicode, PageElement):
  341. def __new__(cls, value):
  342. """Create a new NavigableString.
  343. When unpickling a NavigableString, this method is called with
  344. the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
  345. passed in to the superclass's __new__ or the superclass won't know
  346. how to handle non-ASCII characters.
  347. """
  348. if isinstance(value, unicode):
  349. return unicode.__new__(cls, value)
  350. return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
  351. def __getnewargs__(self):
  352. return (unicode(self),)
  353. def __getattr__(self, attr):
  354. """text.string gives you text. This is for backwards
  355. compatibility for Navigable*String, but for CData* it lets you
  356. get the string without the CData wrapper."""
  357. if attr == 'string':
  358. return self
  359. else:
  360. raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
  361. def encode(self, encoding=DEFAULT_OUTPUT_ENCODING):
  362. return self.decode().encode(encoding)
  363. def decodeGivenEventualEncoding(self, eventualEncoding):
  364. return self
  365. class CData(NavigableString):
  366. def decodeGivenEventualEncoding(self, eventualEncoding):
  367. return u'<![CDATA[' + self + u']]>'
  368. class ProcessingInstruction(NavigableString):
  369. def decodeGivenEventualEncoding(self, eventualEncoding):
  370. output = self
  371. if u'%SOUP-ENCODING%' in output:
  372. output = self.substituteEncoding(output, eventualEncoding)
  373. return u'<?' + output + u'?>'
  374. class Comment(NavigableString):
  375. def decodeGivenEventualEncoding(self, eventualEncoding):
  376. return u'<!--' + self + u'-->'
  377. class Declaration(NavigableString):
  378. def decodeGivenEventualEncoding(self, eventualEncoding):
  379. return u'<!' + self + u'>'
  380. class Tag(PageElement):
  381. """Represents a found HTML tag with its attributes and contents."""
  382. def _invert(h):
  383. "Cheap function to invert a hash."
  384. i = {}
  385. for k,v in h.items():
  386. i[v] = k
  387. return i
  388. XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'",
  389. "quot" : '"',
  390. "amp" : "&",
  391. "lt" : "<",
  392. "gt" : ">" }
  393. XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS)
  394. def _convertEntities(self, match):
  395. """Used in a call to re.sub to replace HTML, XML, and numeric
  396. entities with the appropriate Unicode characters. If HTML
  397. entities are being converted, any unrecognized entities are
  398. escaped."""
  399. x = match.group(1)
  400. if self.convertHTMLEntities and x in name2codepoint:
  401. return unichr(name2codepoint[x])
  402. elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS:
  403. if self.convertXMLEntities:
  404. return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]
  405. else:
  406. return u'&%s;' % x
  407. elif len(x) > 0 and x[0] == '#':
  408. # Handle numeric entities
  409. if len(x) > 1 and x[1] == 'x':
  410. return unichr(int(x[2:], 16))
  411. else:
  412. return unichr(int(x[1:]))
  413. elif self.escapeUnrecognizedEntities:
  414. return u'&amp;%s;' % x
  415. else:
  416. return u'&%s;' % x
  417. def __init__(self, parser, name, attrs=None, parent=None,
  418. previous=None):
  419. "Basic constructor."
  420. # We don't actually store the parser object: that lets extracted
  421. # chunks be garbage-collected
  422. self.parserClass = parser.__class__
  423. self.isSelfClosing = parser.isSelfClosingTag(name)
  424. self.name = name
  425. if attrs == None:
  426. attrs = []
  427. self.attrs = attrs
  428. self.contents = []
  429. self.setup(parent, previous)
  430. self.hidden = False
  431. self.containsSubstitutions = False
  432. self.convertHTMLEntities = parser.convertHTMLEntities
  433. self.convertXMLEntities = parser.convertXMLEntities
  434. self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
  435. def convert(kval):
  436. "Converts HTML, XML and numeric entities in the attribute value."
  437. k, val = kval
  438. if val is None:
  439. return kval
  440. return (k, re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);",
  441. self._convertEntities, val))
  442. self.attrs = map(convert, self.attrs)
  443. def get(self, key, default=None):
  444. """Returns the value of the 'key' attribute for the tag, or
  445. the value given for 'default' if it doesn't have that
  446. attribute."""
  447. return self._getAttrMap().get(key, default)
  448. def has_key(self, key):
  449. return self._getAttrMap().has_key(key)
  450. def __getitem__(self, key):
  451. """tag[key] returns the value of the 'key' attribute for the tag,
  452. and throws an exception if it's not there."""
  453. return self._getAttrMap()[key]
  454. def __iter__(self):
  455. "Iterating over a tag iterates over its contents."
  456. return iter(self.contents)
  457. def __len__(self):
  458. "The length of a tag is the length of its list of contents."
  459. return len(self.contents)
  460. def __contains__(self, x):
  461. return x in self.contents
  462. def __nonzero__(self):
  463. "A tag is non-None even if it has no contents."
  464. return True
  465. def __setitem__(self, key, value):
  466. """Setting tag[key] sets the value of the 'key' attribute for the
  467. tag."""
  468. self._getAttrMap()
  469. self.attrMap[key] = value
  470. found = False
  471. for i in range(0, len(self.attrs)):
  472. if self.attrs[i][0] == key:
  473. self.attrs[i] = (key, value)
  474. found = True
  475. if not found:
  476. self.attrs.append((key, value))
  477. self._getAttrMap()[key] = value
  478. def __delitem__(self, key):
  479. "Deleting tag[key] deletes all 'key' attributes for the tag."
  480. for item in self.attrs:
  481. if item[0] == key:
  482. self.attrs.remove(item)
  483. #We don't break because bad HTML can define the same
  484. #attribute multiple times.
  485. self._getAttrMap()
  486. if self.attrMap.has_key(key):
  487. del self.attrMap[key]
  488. def __call__(self, *args, **kwargs):
  489. """Calling a tag like a function is the same as calling its
  490. findAll() method. Eg. tag('a') returns a list of all the A tags
  491. found within this tag."""
  492. return apply(self.findAll, args, kwargs)
  493. def __getattr__(self, tag):
  494. #print "Getattr %s.%s" % (self.__class__, tag)
  495. if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3:
  496. return self.find(tag[:-3])
  497. elif tag.find('__') != 0:
  498. return self.find(tag)
  499. raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag)
  500. def __eq__(self, other):
  501. """Returns true iff this tag has the same name, the same attributes,
  502. and the same contents (recursively) as the given tag.
  503. NOTE: right now this will return false if two tags have the
  504. same attributes in a different order. Should this be fixed?"""
  505. if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other):
  506. return False
  507. for i in range(0, len(self.contents)):
  508. if self.contents[i] != other.contents[i]:
  509. return False
  510. return True
  511. def __ne__(self, other):
  512. """Returns true iff this tag is not identical to the other tag,
  513. as defined in __eq__."""
  514. return not self == other
  515. def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  516. """Renders this tag as a string."""
  517. return self.decode(eventualEncoding=encoding)
  518. BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|"
  519. + "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)"
  520. + ")")
  521. def _sub_entity(self, x):
  522. """Used with a regular expression to substitute the
  523. appropriate XML entity for an XML special character."""
  524. return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";"
  525. def __unicode__(self):
  526. return self.decode()
  527. def __str__(self):
  528. return self.encode()
  529. def encode(self, encoding=DEFAULT_OUTPUT_ENCODING,
  530. prettyPrint=False, indentLevel=0):
  531. return self.decode(prettyPrint, indentLevel, encoding).encode(encoding)
  532. def decode(self, prettyPrint=False, indentLevel=0,
  533. eventualEncoding=DEFAULT_OUTPUT_ENCODING):
  534. """Returns a string or Unicode representation of this tag and
  535. its contents. To get Unicode, pass None for encoding."""
  536. attrs = []
  537. if self.attrs:
  538. for key, val in self.attrs:
  539. fmt = '%s="%s"'
  540. if isString(val):
  541. if (self.containsSubstitutions
  542. and eventualEncoding is not None
  543. and '%SOUP-ENCODING%' in val):
  544. val = self.substituteEncoding(val, eventualEncoding)
  545. # The attribute value either:
  546. #
  547. # * Contains no embedded double quotes or single quotes.
  548. # No problem: we enclose it in double quotes.
  549. # * Contains embedded single quotes. No problem:
  550. # double quotes work here too.
  551. # * Contains embedded double quotes. No problem:
  552. # we enclose it in single quotes.
  553. # * Embeds both single _and_ double quotes. This
  554. # can't happen naturally, but it can happen if
  555. # you modify an attribute value after parsing
  556. # the document. Now we have a bit of a
  557. # problem. We solve it by enclosing the
  558. # attribute in single quotes, and escaping any
  559. # embedded single quotes to XML entities.
  560. if '"' in val:
  561. fmt = "%s='%s'"
  562. if "'" in val:
  563. # TODO: replace with apos when
  564. # appropriate.
  565. val = val.replace("'", "&squot;")
  566. # Now we're okay w/r/t quotes. But the attribute
  567. # value might also contain angle brackets, or
  568. # ampersands that aren't part of entities. We need
  569. # to escape those to XML entities too.
  570. val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val)
  571. if val is None:
  572. # Handle boolean attributes.
  573. decoded = key
  574. else:
  575. decoded = fmt % (key, val)
  576. attrs.append(decoded)
  577. close = ''
  578. closeTag = ''
  579. if self.isSelfClosing:
  580. close = ' /'
  581. else:
  582. closeTag = '</%s>' % self.name
  583. indentTag, indentContents = 0, 0
  584. if prettyPrint:
  585. indentTag = indentLevel
  586. space = (' ' * (indentTag-1))
  587. indentContents = indentTag + 1
  588. contents = self.decodeContents(prettyPrint, indentContents,
  589. eventualEncoding)
  590. if self.hidden:
  591. s = contents
  592. else:
  593. s = []
  594. attributeString = ''
  595. if attrs:
  596. attributeString = ' ' + ' '.join(attrs)
  597. if prettyPrint:
  598. s.append(space)
  599. s.append('<%s%s%s>' % (self.name, attributeString, close))
  600. if prettyPrint:
  601. s.append("\n")
  602. s.append(contents)
  603. if prettyPrint and contents and contents[-1] != "\n":
  604. s.append("\n")
  605. if prettyPrint and closeTag:
  606. s.append(space)
  607. s.append(closeTag)
  608. if prettyPrint and closeTag and self.nextSibling:
  609. s.append("\n")
  610. s = ''.join(s)
  611. return s
  612. def decompose(self):
  613. """Recursively destroys the contents of this tree."""
  614. contents = [i for i in self.contents]
  615. for i in contents:
  616. if isinstance(i, Tag):
  617. i.decompose()
  618. else:
  619. i.extract()
  620. self.extract()
  621. def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING):
  622. return self.encode(encoding, True)
  623. def encodeContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
  624. prettyPrint=False, indentLevel=0):
  625. return self.decodeContents(prettyPrint, indentLevel).encode(encoding)
  626. def decodeContents(self, prettyPrint=False, indentLevel=0,
  627. eventualEncoding=DEFAULT_OUTPUT_ENCODING):
  628. """Renders the contents of this tag as a string in the given
  629. encoding. If encoding is None, returns a Unicode string.."""
  630. s=[]
  631. for c in self:
  632. text = None
  633. if isinstance(c, NavigableString):
  634. text = c.decodeGivenEventualEncoding(eventualEncoding)
  635. elif isinstance(c, Tag):
  636. s.append(c.decode(prettyPrint, indentLevel, eventualEncoding))
  637. if text and prettyPrint:
  638. text = text.strip()
  639. if text:
  640. if prettyPrint:
  641. s.append(" " * (indentLevel-1))
  642. s.append(text)
  643. if prettyPrint:
  644. s.append("\n")
  645. return ''.join(s)
  646. #Soup methods
  647. def find(self, name=None, attrs={}, recursive=True, text=None,
  648. **kwargs):
  649. """Return only the first child of this Tag matching the given
  650. criteria."""
  651. r = None
  652. l = self.findAll(name, attrs, recursive, text, 1, **kwargs)
  653. if l:
  654. r = l[0]
  655. return r
  656. findChild = find
  657. def findAll(self, name=None, attrs={}, recursive=True, text=None,
  658. limit=None, **kwargs):
  659. """Extracts a list of Tag objects that match the given
  660. criteria. You can specify the name of the Tag and any
  661. attributes you want the Tag to have.
  662. The value of a key-value pair in the 'attrs' map can be a
  663. string, a list of strings, a regular expression object, or a
  664. callable that takes a string and returns whether or not the
  665. string matches for some custom definition of 'matches'. The
  666. same is true of the tag name."""
  667. generator = self.recursiveChildGenerator
  668. if not recursive:
  669. generator = self.childGenerator
  670. return self._findAll(name, attrs, text, limit, generator, **kwargs)
  671. findChildren = findAll
  672. # Pre-3.x compatibility methods. Will go away in 4.0.
  673. first = find
  674. fetch = findAll
  675. def fetchText(self, text=None, recursive=True, limit=None):
  676. return self.findAll(text=text, recursive=recursive, limit=limit)
  677. def firstText(self, text=None, recursive=True):
  678. return self.find(text=text, recursive=recursive)
  679. # 3.x compatibility methods. Will go away in 4.0.
  680. def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
  681. prettyPrint=False, indentLevel=0):
  682. if encoding is None:
  683. return self.decodeContents(prettyPrint, indentLevel, encoding)
  684. else:
  685. return self.encodeContents(encoding, prettyPrint, indentLevel)
  686. #Private methods
  687. def _getAttrMap(self):
  688. """Initializes a map representation of this tag's attributes,
  689. if not already initialized."""
  690. if not getattr(self, 'attrMap'):
  691. self.attrMap = {}
  692. for (key, value) in self.attrs:
  693. self.attrMap[key] = value
  694. return self.attrMap
  695. #Generator methods
  696. def recursiveChildGenerator(self):
  697. if not len(self.contents):
  698. raise StopIteration
  699. stopNode = self._lastRecursiveChild().next
  700. current = self.contents[0]
  701. while current is not stopNode:
  702. yield current
  703. current = current.next
  704. def childGenerator(self):
  705. if not len(self.contents):
  706. raise StopIteration
  707. current = self.contents[0]
  708. while current:
  709. yield current
  710. current = current.nextSibling
  711. raise StopIteration
  712. # Next, a couple classes to represent queries and their results.
  713. class SoupStrainer:
  714. """Encapsulates a number of ways of matching a markup element (tag or
  715. text)."""
  716. def __init__(self, name=None, attrs={}, text=None, **kwargs):
  717. self.name = name
  718. if isString(attrs):
  719. kwargs['class'] = attrs
  720. attrs = None
  721. if kwargs:
  722. if attrs:
  723. attrs = attrs.copy()
  724. attrs.update(kwargs)
  725. else:
  726. attrs = kwargs
  727. self.attrs = attrs
  728. self.text = text
  729. def __str__(self):
  730. if self.text:
  731. return self.text
  732. else:
  733. return "%s|%s" % (self.name, self.attrs)
  734. def searchTag(self, markupName=None, markupAttrs={}):
  735. found = None
  736. markup = None
  737. if isinstance(markupName, Tag):
  738. markup = markupName
  739. markupAttrs = markup
  740. callFunctionWithTagData = callable(self.name) \
  741. and not isinstance(markupName, Tag)
  742. if (not self.name) \
  743. or callFunctionWithTagData \
  744. or (markup and self._matches(markup, self.name)) \
  745. or (not markup and self._matches(markupName, self.name)):
  746. if callFunctionWithTagData:
  747. match = self.name(markupName, markupAttrs)
  748. else:
  749. match = True
  750. markupAttrMap = None
  751. for attr, matchAgainst in self.attrs.items():
  752. if not markupAttrMap:
  753. if hasattr(markupAttrs, 'get'):
  754. markupAttrMap = markupAttrs
  755. else:
  756. markupAttrMap = {}
  757. for k,v in markupAttrs:
  758. markupAttrMap[k] = v
  759. attrValue = markupAttrMap.get(attr)
  760. if not self._matches(attrValue, matchAgainst):
  761. match = False
  762. break
  763. if match:
  764. if markup:
  765. found = markup
  766. else:
  767. found = markupName
  768. return found
  769. def search(self, markup):
  770. #print 'looking for %s in %s' % (self, markup)
  771. found = None
  772. # If given a list of items, scan it for a text element that
  773. # matches.
  774. if isList(markup) and not isinstance(markup, Tag):
  775. for element in markup:
  776. if isinstance(element, NavigableString) \
  777. and self.search(element):
  778. found = element
  779. break
  780. # If it's a Tag, make sure its name or attributes match.
  781. # Don't bother with Tags if we're searching for text.
  782. elif isinstance(markup, Tag):
  783. if not self.text:
  784. found = self.searchTag(markup)
  785. # If it's text, make sure the text matches.
  786. elif isinstance(markup, NavigableString) or \
  787. isString(markup):
  788. if self._matches(markup, self.text):
  789. found = markup
  790. else:
  791. raise Exception, "I don't know how to match against a %s" \
  792. % markup.__class__
  793. return found
  794. def _matches(self, markup, matchAgainst):
  795. #print "Matching %s against %s" % (markup, matchAgainst)
  796. result = False
  797. if matchAgainst == True and type(matchAgainst) == types.BooleanType:
  798. result = markup != None
  799. elif callable(matchAgainst):
  800. result = matchAgainst(markup)
  801. else:
  802. #Custom match methods take the tag as an argument, but all
  803. #other ways of matching match the tag name as a string.
  804. if isinstance(markup, Tag):
  805. markup = markup.name
  806. if markup is not None and not isString(markup):
  807. markup = unicode(markup)
  808. #Now we know that chunk is either a string, or None.
  809. if hasattr(matchAgainst, 'match'):
  810. # It's a regexp object.
  811. result = markup and matchAgainst.search(markup)
  812. elif (isList(matchAgainst)
  813. and (markup is not None or not isString(matchAgainst))):
  814. result = markup in matchAgainst
  815. elif hasattr(matchAgainst, 'items'):
  816. result = markup.has_key(matchAgainst)
  817. elif matchAgainst and isString(markup):
  818. if isinstance(markup, unicode):
  819. matchAgainst = unicode(matchAgainst)
  820. else:
  821. matchAgainst = str(matchAgainst)
  822. if not result:
  823. result = matchAgainst == markup
  824. return result
  825. class ResultSet(list):
  826. """A ResultSet is just a list that keeps track of the SoupStrainer
  827. that created it."""
  828. def __init__(self, source):
  829. list.__init__([])
  830. self.source = source
  831. # Now, some helper functions.
  832. def isList(l):
  833. """Convenience method that works with all 2.x versions of Python
  834. to determine whether or not something is listlike."""
  835. return ((hasattr(l, '__iter__') and not isString(l))
  836. or (type(l) in (types.ListType, types.TupleType)))
  837. def isString(s):
  838. """Convenience method that works with all 2.x versions of Python
  839. to determine whether or not something is stringlike."""
  840. try:
  841. return isinstance(s, unicode) or isinstance(s, basestring)
  842. except NameError:
  843. return isinstance(s, str)
  844. def buildTagMap(default, *args):
  845. """Turns a list of maps, lists, or scalars into a single map.
  846. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and
  847. NESTING_RESET_TAGS maps out of lists and partial maps."""
  848. built = {}
  849. for portion in args:
  850. if hasattr(portion, 'items'):
  851. #It's a map. Merge it.
  852. for k,v in portion.items():
  853. built[k] = v
  854. elif isList(portion) and not isString(portion):
  855. #It's a list. Map each item to the default.
  856. for k in portion:
  857. built[k] = default
  858. else:
  859. #It's a scalar. Map it to the default.
  860. built[portion] = default
  861. return built
  862. # Now, the parser classes.
  863. class HTMLParserBuilder(HTMLParser):
  864. def __init__(self, soup):
  865. HTMLParser.__init__(self)
  866. self.soup = soup
  867. # We inherit feed() and reset().
  868. def handle_starttag(self, name, attrs):
  869. if name == 'meta':
  870. self.soup.extractCharsetFromMeta(attrs)
  871. else:
  872. self.soup.unknown_starttag(name, attrs)
  873. def handle_endtag(self, name):
  874. self.soup.unknown_endtag(name)
  875. def handle_data(self, content):
  876. self.soup.handle_data(content)
  877. def _toStringSubclass(self, text, subclass):
  878. """Adds a certain piece of text to the tree as a NavigableString
  879. subclass."""
  880. self.soup.endData()
  881. self.handle_data(text)
  882. self.soup.endData(subclass)
  883. def handle_pi(self, text):
  884. """Handle a processing instruction as a ProcessingInstruction
  885. object, possibly one with a %SOUP-ENCODING% slot into which an
  886. encoding will be plugged later."""
  887. if text[:3] == "xml":
  888. text = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
  889. self._toStringSubclass(text, ProcessingInstruction)
  890. def handle_comment(self, text):
  891. "Handle comments as Comment objects."
  892. self._toStringSubclass(text, Comment)
  893. def handle_charref(self, ref):
  894. "Handle character references as data."
  895. if self.soup.convertEntities:
  896. data = unichr(int(ref))
  897. else:
  898. data = '&#%s;' % ref
  899. self.handle_data(data)
  900. def handle_entityref(self, ref):
  901. """Handle entity references as data, possibly converting known
  902. HTML and/or XML entity references to the corresponding Unicode
  903. characters."""
  904. data = None
  905. if self.soup.convertHTMLEntities:
  906. try:
  907. data = unichr(name2codepoint[ref])
  908. except KeyError:
  909. pass
  910. if not data and self.soup.convertXMLEntities:
  911. data = self.soup.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref)
  912. if not data and self.soup.convertHTMLEntities and \
  913. not self.soup.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref):
  914. # TODO: We've got a problem here. We're told this is
  915. # an entity reference, but it's not an XML entity
  916. # reference or an HTML entity reference. Nonetheless,
  917. # the logical thing to do is to pass it through as an
  918. # unrecognized entity reference.
  919. #
  920. # Except: when the input is "&carol;" this function
  921. # will be called with input "carol". When the input is
  922. # "AT&T", this function will be called with input
  923. # "T". We have no way of knowing whether a semicolon
  924. # was present originally, so we don't know whether
  925. # this is an unknown entity or just a misplaced
  926. # ampersand.
  927. #
  928. # The more common case is a misplaced ampersand, so I
  929. # escape the ampersand and omit the trailing semicolon.
  930. data = "&amp;%s" % ref
  931. if not data:
  932. # This case is different from the one above, because we
  933. # haven't already gone through a supposedly comprehensive
  934. # mapping of entities to Unicode characters. We might not
  935. # have gone through any mapping at all. So the chances are
  936. # very high that this is a real entity, and not a
  937. # misplaced ampersand.
  938. data = "&%s;" % ref
  939. self.handle_data(data)
  940. def handle_decl(self, data):
  941. "Handle DOCTYPEs and the like as Declaration objects."
  942. self._toStringSubclass(data, Declaration)
  943. def parse_declaration(self, i):
  944. """Treat a bogus SGML declaration as raw data. Treat a CDATA
  945. declaration as a CData object."""
  946. j = None
  947. if self.rawdata[i:i+9] == '<![CDATA[':
  948. k = self.rawdata.find(']]>', i)
  949. if k == -1:
  950. k = len(self.rawdata)
  951. data = self.rawdata[i+9:k]
  952. j = k+3
  953. self._toStringSubclass(data, CData)
  954. else:
  955. try:
  956. j = HTMLParser.parse_declaration(self, i)
  957. except HTMLParseError:
  958. toHandle = self.rawdata[i:]
  959. self.handle_data(toHandle)
  960. j = i + len(toHandle)
  961. return j
  962. class BeautifulStoneSoup(Tag):
  963. """This class contains the basic parser and search code. It defines
  964. a parser that knows nothing about tag behavior except for the
  965. following:
  966. You can't close a tag without closing all the tags it encloses.
  967. That is, "<foo><bar></foo>" actually means
  968. "<foo><bar></bar></foo>".
  969. [Another possible explanation is "<foo><bar /></foo>", but since
  970. this class defines no SELF_CLOSING_TAGS, it will never use that
  971. explanation.]
  972. This class is useful for parsing XML or made-up markup languages,
  973. or when BeautifulSoup makes an assumption counter to what you were
  974. expecting."""
  975. SELF_CLOSING_TAGS = {}
  976. NESTABLE_TAGS = {}
  977. RESET_NESTING_TAGS = {}
  978. QUOTE_TAGS = {}
  979. PRESERVE_WHITESPACE_TAGS = []
  980. MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'),
  981. lambda x: x.group(1) + ' />'),
  982. (re.compile('<!\s+([^<>]*)>'),
  983. lambda x: '<!' + x.group(1) + '>')
  984. ]
  985. ROOT_TAG_NAME = u'[document]'
  986. HTML_ENTITIES = "html"
  987. XML_ENTITIES = "xml"
  988. XHTML_ENTITIES = "xhtml"
  989. # TODO: This only exists for backwards-compatibility
  990. ALL_ENTITIES = XHTML_ENTITIES
  991. # Used when determining whether a text node is all whitespace and
  992. # can be replaced with a single space. A text node that contains
  993. # fancy Unicode spaces (usually non-breaking) should be left
  994. # alone.
  995. STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, }
  996. def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None,
  997. markupMassage=True, smartQuotesTo=XML_ENTITIES,
  998. convertEntities=None, selfClosingTags=None, isHTML=False,
  999. builder=HTMLParserBuilder):
  1000. """The Soup object is initialized as the 'root tag', and the
  1001. provided markup (which can be a string or a file-like object)
  1002. is fed into the underlying parser.
  1003. HTMLParser will process most bad HTML, and the BeautifulSoup
  1004. class has some tricks for dealing with some HTML that kills
  1005. HTMLParser, but Beautiful Soup can nonetheless choke or lose data
  1006. if your data uses self-closing tags or declarations
  1007. incorrectly.
  1008. By default, Beautiful Soup uses regexes to sanitize input,
  1009. avoiding the vast majority of these problems. If the problems
  1010. don't apply to you, pass in False for markupMassage, and
  1011. you'll get better performance.
  1012. The default parser massage techniques fix the two most common
  1013. instances of invalid HTML that choke HTMLParser:
  1014. <br/> (No space between name of closing tag and tag close)
  1015. <! --Comment--> (Extraneous whitespace in declaration)
  1016. You can pass in a custom list of (RE object, replace method)
  1017. tuples to get Beautiful Soup to scrub your input the way you
  1018. want."""
  1019. self.parseOnlyThese = parseOnlyThese
  1020. self.fromEncoding = fromEncoding
  1021. self.smartQuotesTo = smartQuotesTo
  1022. self.convertEntities = convertEntities
  1023. # Set the rules for how we'll deal with the entities we
  1024. # encounter
  1025. if self.convertEntities:
  1026. # It doesn't make sense to convert encoded characters to
  1027. # entities even while you're converting entities to Unicode.
  1028. # Just convert it all to Unicode.
  1029. self.smartQuotesTo = None
  1030. if convertEntities == self.HTML_ENTITIES:
  1031. self.convertXMLEntities = False
  1032. self.convertHTMLEntities = True
  1033. self.escapeUnrecognizedEntities = True
  1034. elif convertEntities == self.XHTML_ENTITIES:
  1035. self.convertXMLEntities = True
  1036. self.convertHTMLEntities = True
  1037. self.escapeUnrecognizedEntities = False
  1038. elif convertEntities == self.XML_ENTITIES:
  1039. self.convertXMLEntities = True
  1040. self.convertHTMLEntities = False
  1041. self.escapeUnrecognizedEntities = False
  1042. else:
  1043. self.convertXMLEntities = False
  1044. self.convertHTMLEntities = False
  1045. self.escapeUnrecognizedEntities = False
  1046. self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
  1047. self.builder = builder(self)
  1048. self.reset()
  1049. if hasattr(markup, 'read'): # It's a file-type object.
  1050. markup = markup.read()
  1051. self.markup = markup
  1052. self.markupMassage = markupMassage
  1053. try:
  1054. self._feed(isHTML=isHTML)
  1055. except StopParsing:
  1056. pass
  1057. self.markup = None # The markup can now be GCed.
  1058. self.builder = None # So can the builder.
  1059. def _feed(self, inDocumentEncoding=None, isHTML=False):
  1060. # Convert the document to Unicode.
  1061. markup = self.markup
  1062. if isinstance(markup, unicode):
  1063. if not hasattr(self, 'originalEncoding'):
  1064. self.originalEncoding = None
  1065. else:
  1066. dammit = UnicodeDammit\
  1067. (markup, [self.fromEncoding, inDocumentEncoding],
  1068. smartQuotesTo=self.smartQuotesTo, isHTML=isHTML)
  1069. markup = dammit.unicode
  1070. self.originalEncoding = dammit.originalEncoding
  1071. self.declaredHTMLEncoding = dammit.declaredHTMLEncoding
  1072. if markup:
  1073. if self.markupMassage:
  1074. if not isList(self.markupMassage):
  1075. self.markupMassage = self.MARKUP_MASSAGE
  1076. for fix, m in self.markupMassage:
  1077. markup = fix.sub(m, markup)
  1078. # TODO: We get rid of markupMassage so that the
  1079. # soup object can be deepcopied later on. Some
  1080. # Python installations can't copy regexes. If anyone
  1081. # was relying on the existence of markupMassage, this
  1082. # might cause problems.
  1083. del(self.markupMassage)
  1084. self.builder.reset()
  1085. self.builder.feed(markup)
  1086. # Close out any unfinished strings and close all the open tags.
  1087. self.endData()
  1088. while self.currentTag.name != self.ROOT_TAG_NAME:
  1089. self.popTag()
  1090. def isSelfClosingTag(self, name):
  1091. """Returns true iff the given string is the name of a
  1092. self-closing tag according to this parser."""
  1093. return self.SELF_CLOSING_TAGS.has_key(name) \
  1094. or self.instanceSelfClosingTags.has_key(name)
  1095. def reset(self):
  1096. Tag.__init__(self, self, self.ROOT_TAG_NAME)
  1097. self.hidden = 1
  1098. self.builder.reset()
  1099. self.currentData = []
  1100. self.currentTag = None
  1101. self.tagStack = []
  1102. self.quoteStack = []
  1103. self.pushTag(self)
  1104. def popTag(self):
  1105. tag = self.tagStack.pop()
  1106. # Tags with just one string-owning child get the child as a
  1107. # 'string' property, so that soup.tag.string is shorthand for
  1108. # soup.tag.contents[0]
  1109. if len(self.currentTag.contents) == 1 and \
  1110. isinstance(self.currentTag.contents[0], NavigableString):
  1111. self.currentTag.string = self.currentTag.contents[0]
  1112. #print "Pop", tag.name
  1113. if self.tagStack:
  1114. self.currentTag = self.tagStack[-1]
  1115. return self.currentTag
  1116. def pushTag(self, tag):
  1117. #print "Push", tag.name
  1118. if self.currentTag:
  1119. self.currentTag.contents.append(tag)
  1120. self.tagStack.append(tag)
  1121. self.currentTag = self.tagStack[-1]
  1122. def endData(self, containerClass=NavigableString):
  1123. if

Large files files are truncated, but you can click here to view the full file