PageRenderTime 57ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/crunchy/src/element_tree/BeautifulSoup.py

http://crunchy.googlecode.com/
Python | 2015 lines | 1804 code | 82 blank | 129 comment | 132 complexity | 5ae762376121553a299d59adf83e77a4 MD5 | raw file
Possible License(s): BSD-3-Clause

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

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

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