PageRenderTime 67ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/slides/BeautifulSoup.py

https://bitbucket.org/akamil/61a-sp13-website
Python | 2014 lines | 1876 code | 62 blank | 76 comment | 107 complexity | bac2be6ae9673ee5096e20e8b714c9cd MD5 | raw file

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

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