PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/scripts/python/xgoogle/BeautifulSoup.py

https://bitbucket.org/JasonGross/alphabets
Python | 1934 lines | 1780 code | 74 blank | 80 comment | 110 complexity | 039b200f1947e22cb2a13c5a0d842fd3 MD5 | raw file
Possible License(s): BSD-3-Clause-No-Nuclear-License-2014, Apache-2.0, MPL-2.0-no-copyleft-exception

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

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