PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/BeautifulSoup.py

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

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