PageRenderTime 56ms CodeModel.GetById 11ms 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
  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
  1122. if self.currentTag:
  1123. self.currentTag.contents.append(tag)
  1124. self.tagStack.append(tag)
  1125. self.currentTag = self.tagStack[-1]
  1126. def endData(self, containerClass=NavigableString):
  1127. if self.currentData:
  1128. currentData = u''.join(self.currentData)
  1129. if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and
  1130. not set([tag.name for tag in self.tagStack]).intersection(
  1131. self.PRESERVE_WHITESPACE_TAGS)):
  1132. if '\n' in currentData:
  1133. currentData = '\n'
  1134. else:
  1135. currentData = ' '
  1136. self.currentData = []
  1137. if self.parseOnlyThese and len(self.tagStack) <= 1 and \
  1138. (not self.parseOnlyThese.text or \
  1139. not self.parseOnlyThese.search(currentData)):
  1140. return
  1141. o = containerClass(currentData)
  1142. o.setup(self.currentTag, self.previous)
  1143. if self.previous:
  1144. self.previous.next = o
  1145. self.previous = o
  1146. self.currentTag.contents.append(o)
  1147. def _popToTag(self, name, inclusivePop=True):
  1148. """Pops the tag stack up to and including the most recent
  1149. instance of the given tag. If inclusivePop is false, pops the tag
  1150. stack up to but *not* including the most recent instqance of
  1151. the given tag."""
  1152. #print "Popping to %s" % name
  1153. if name == self.ROOT_TAG_NAME:
  1154. return
  1155. numPops = 0
  1156. mostRecentTag = None
  1157. for i in range(len(self.tagStack)-1, 0, -1):
  1158. if name == self.tagStack[i].name:
  1159. numPops = len(self.tagStack)-i
  1160. break
  1161. if not inclusivePop:
  1162. numPops = numPops - 1
  1163. for i in range(0, numPops):
  1164. mostRecentTag = self.popTag()
  1165. return mostRecentTag
  1166. def _smartPop(self, name):
  1167. """We need to pop up to the previous tag of this type, unless
  1168. one of this tag's nesting reset triggers comes between this
  1169. tag and the previous tag of this type, OR unless this tag is a
  1170. generic nesting trigger and another generic nesting trigger
  1171. comes between this tag and the previous tag of this type.
  1172. Examples:
  1173. <p>Foo<b>Bar *<p>* should pop to 'p', not 'b'.
  1174. <p>Foo<table>Bar *<p>* should pop to 'table', not 'p'.
  1175. <p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'.
  1176. <li><ul><li> *<li>* should pop to 'ul', not the first 'li'.
  1177. <tr><table><tr> *<tr>* should pop to 'table', not the first 'tr'
  1178. <td><tr><td> *<td>* should pop to 'tr', not the first 'td'
  1179. """
  1180. nestingResetTriggers = self.NESTABLE_TAGS.get(name)
  1181. isNestable = nestingResetTriggers != None
  1182. isResetNesting = self.RESET_NESTING_TAGS.has_key(name)
  1183. popTo = None
  1184. inclusive = True
  1185. for i in range(len(self.tagStack)-1, 0, -1):
  1186. p = self.tagStack[i]
  1187. if (not p or p.name == name) and not isNestable:
  1188. #Non-nestable tags get popped to the top or to their
  1189. #last occurance.
  1190. popTo = name
  1191. break
  1192. if (nestingResetTriggers != None
  1193. and p.name in nestingResetTriggers) \
  1194. or (nestingResetTriggers == None and isResetNesting
  1195. and self.RESET_NESTING_TAGS.has_key(p.name)):
  1196. #If we encounter one of the nesting reset triggers
  1197. #peculiar to this tag, or we encounter another tag
  1198. #that causes nesting to reset, pop up to but not
  1199. #including that tag.
  1200. popTo = p.name
  1201. inclusive = False
  1202. break
  1203. p = p.parent
  1204. if popTo:
  1205. self._popToTag(popTo, inclusive)
  1206. def unknown_starttag(self, name, attrs, selfClosing=0):
  1207. #print "Start tag %s: %s" % (name, attrs)
  1208. if self.quoteStack:
  1209. #This is not a real tag.
  1210. #print "<%s> is not real!" % name
  1211. attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs))
  1212. self.handle_data('<%s%s>' % (name, attrs))
  1213. return
  1214. self.endData()
  1215. if not self.isSelfClosingTag(name) and not selfClosing:
  1216. self._smartPop(name)
  1217. if self.parseOnlyThese and len(self.tagStack) <= 1 \
  1218. and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)):
  1219. return
  1220. tag = Tag(self, name, attrs, self.currentTag, self.previous)
  1221. if self.previous:
  1222. self.previous.next = tag
  1223. self.previous = tag
  1224. self.pushTag(tag)
  1225. if selfClosing or self.isSelfClosingTag(name):
  1226. self.popTag()
  1227. if name in self.QUOTE_TAGS:
  1228. #print "Beginning quote (%s)" % name
  1229. self.quoteStack.append(name)
  1230. self.literal = 1
  1231. return tag
  1232. def unknown_endtag(self, name):
  1233. #print "End tag %s" % name
  1234. if self.quoteStack and self.quoteStack[-1] != name:
  1235. #This is not a real end tag.
  1236. #print "</%s> is not real!" % name
  1237. self.handle_data('</%s>' % name)
  1238. return
  1239. self.endData()
  1240. self._popToTag(name)
  1241. if self.quoteStack and self.quoteStack[-1] == name:
  1242. self.quoteStack.pop()
  1243. self.literal = (len(self.quoteStack) > 0)
  1244. def handle_data(self, data):
  1245. self.currentData.append(data)
  1246. def extractCharsetFromMeta(self, attrs):
  1247. self.unknown_starttag('meta', attrs)
  1248. class BeautifulSoup(BeautifulStoneSoup):
  1249. """This parser knows the following facts about HTML:
  1250. * Some tags have no closing tag and should be interpreted as being
  1251. closed as soon as they are encountered.
  1252. * The text inside some tags (ie. 'script') may contain tags which
  1253. are not really part of the document and which should be parsed
  1254. as text, not tags. If you want to parse the text as tags, you can
  1255. always fetch it and parse it explicitly.
  1256. * Tag nesting rules:
  1257. Most tags can't be nested at all. For instance, the occurance of
  1258. a <p> tag should implicitly close the previous <p> tag.
  1259. <p>Para1<p>Para2
  1260. should be transformed into:
  1261. <p>Para1</p><p>Para2
  1262. Some tags can be nested arbitrarily. For instance, the occurance
  1263. of a <blockquote> tag should _not_ implicitly close the previous
  1264. <blockquote> tag.
  1265. Alice said: <blockquote>Bob said: <blockquote>Blah
  1266. should NOT be transformed into:
  1267. Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah
  1268. Some tags can be nested, but the nesting is reset by the
  1269. interposition of other tags. For instance, a <tr> tag should
  1270. implicitly close the previous <tr> tag within the same <table>,
  1271. but not close a <tr> tag in another table.
  1272. <table><tr>Blah<tr>Blah
  1273. should be transformed into:
  1274. <table><tr>Blah</tr><tr>Blah
  1275. but,
  1276. <tr>Blah<table><tr>Blah
  1277. should NOT be transformed into
  1278. <tr>Blah<table></tr><tr>Blah
  1279. Differing assumptions about tag nesting rules are a major source
  1280. of problems with the BeautifulSoup class. If BeautifulSoup is not
  1281. treating as nestable a tag your page author treats as nestable,
  1282. try ICantBelieveItsBeautifulSoup, MinimalSoup, or
  1283. BeautifulStoneSoup before writing your own subclass."""
  1284. def __init__(self, *args, **kwargs):
  1285. if not kwargs.has_key('smartQuotesTo'):
  1286. kwargs['smartQuotesTo'] = self.HTML_ENTITIES
  1287. kwargs['isHTML'] = True
  1288. BeautifulStoneSoup.__init__(self, *args, **kwargs)
  1289. SELF_CLOSING_TAGS = buildTagMap(None,
  1290. ['br' , 'hr', 'input', 'img', 'meta',
  1291. 'spacer', 'link', 'frame', 'base'])
  1292. PRESERVE_WHITESPACE_TAGS = set(['pre', 'textarea'])
  1293. QUOTE_TAGS = {'script' : None, 'textarea' : None}
  1294. #According to the HTML standard, each of these inline tags can
  1295. #contain another tag of the same type. Furthermore, it's common
  1296. #to actually use these tags this way.
  1297. NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup',
  1298. 'center']
  1299. #According to the HTML standard, these block tags can contain
  1300. #another tag of the same type. Furthermore, it's common
  1301. #to actually use these tags this way.
  1302. NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
  1303. #Lists can contain other lists, but there are restrictions.
  1304. NESTABLE_LIST_TAGS = { 'ol' : [],
  1305. 'ul' : [],
  1306. 'li' : ['ul', 'ol'],
  1307. 'dl' : [],
  1308. 'dd' : ['dl'],
  1309. 'dt' : ['dl'] }
  1310. #Tables can contain other tables, but there are restrictions.
  1311. NESTABLE_TABLE_TAGS = {'table' : [],
  1312. 'tr' : ['table', 'tbody', 'tfoot', 'thead'],
  1313. 'td' : ['tr'],
  1314. 'th' : ['tr'],
  1315. 'thead' : ['table'],
  1316. 'tbody' : ['table'],
  1317. 'tfoot' : ['table'],
  1318. }
  1319. NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre']
  1320. #If one of these tags is encountered, all tags up to the next tag of
  1321. #this type are popped.
  1322. RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript',
  1323. NON_NESTABLE_BLOCK_TAGS,
  1324. NESTABLE_LIST_TAGS,
  1325. NESTABLE_TABLE_TAGS)
  1326. NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS,
  1327. NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS)
  1328. # Used to detect the charset in a META tag; see start_meta
  1329. CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M)
  1330. def extractCharsetFromMeta(self, attrs):
  1331. """Beautiful Soup can detect a charset included in a META tag,
  1332. try to convert the document to that charset, and re-parse the
  1333. document from the beginning."""
  1334. httpEquiv = None
  1335. contentType = None
  1336. contentTypeIndex = None
  1337. tagNeedsEncodingSubstitution = False
  1338. for i in range(0, len(attrs)):
  1339. key, value = attrs[i]
  1340. key = key.lower()
  1341. if key == 'http-equiv':
  1342. httpEquiv = value
  1343. elif key == 'content':
  1344. contentType = value
  1345. contentTypeIndex = i
  1346. if httpEquiv and contentType: # It's an interesting meta tag.
  1347. match = self.CHARSET_RE.search(contentType)
  1348. if match:
  1349. if (self.declaredHTMLEncoding is not None or
  1350. self.originalEncoding == self.fromEncoding):
  1351. # An HTML encoding was sniffed while converting
  1352. # the document to Unicode, or an HTML encoding was
  1353. # sniffed during a previous pass through the
  1354. # document, or an encoding was specified
  1355. # explicitly and it worked. Rewrite the meta tag.
  1356. def rewrite(match):
  1357. return match.group(1) + "%SOUP-ENCODING%"
  1358. newAttr = self.CHARSET_RE.sub(rewrite, contentType)
  1359. attrs[contentTypeIndex] = (attrs[contentTypeIndex][0],
  1360. newAttr)
  1361. tagNeedsEncodingSubstitution = True
  1362. else:
  1363. # This is our first pass through the document.
  1364. # Go through it again with the encoding information.
  1365. newCharset = match.group(3)
  1366. if newCharset and newCharset != self.originalEncoding:
  1367. self.declaredHTMLEncoding = newCharset
  1368. self._feed(self.declaredHTMLEncoding)
  1369. raise StopParsing
  1370. pass
  1371. tag = self.unknown_starttag("meta", attrs)
  1372. if tag and tagNeedsEncodingSubstitution:
  1373. tag.containsSubstitutions = True
  1374. class StopParsing(Exception):
  1375. pass
  1376. class ICantBelieveItsBeautifulSoup(BeautifulSoup):
  1377. """The BeautifulSoup class is oriented towards skipping over
  1378. common HTML errors like unclosed tags. However, sometimes it makes
  1379. errors of its own. For instance, consider this fragment:
  1380. <b>Foo<b>Bar</b></b>
  1381. This is perfectly valid (if bizarre) HTML. However, the
  1382. BeautifulSoup class will implicitly close the first b tag when it
  1383. encounters the second 'b'. It will think the author wrote
  1384. "<b>Foo<b>Bar", and didn't close the first 'b' tag, because
  1385. there's no real-world reason to bold something that's already
  1386. bold. When it encounters '</b></b>' it will close two more 'b'
  1387. tags, for a grand total of three tags closed instead of two. This
  1388. can throw off the rest of your document structure. The same is
  1389. true of a number of other tags, listed below.
  1390. It's much more common for someone to forget to close a 'b' tag
  1391. than to actually use nested 'b' tags, and the BeautifulSoup class
  1392. handles the common case. This class handles the not-co-common
  1393. case: where you can't believe someone wrote what they did, but
  1394. it's valid HTML and BeautifulSoup screwed up by assuming it
  1395. wouldn't be."""
  1396. I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \
  1397. ['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong',
  1398. 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b',
  1399. 'big']
  1400. I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript']
  1401. NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS,
  1402. I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS,
  1403. I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS)
  1404. class MinimalSoup(BeautifulSoup):
  1405. """The MinimalSoup class is for parsing HTML that contains
  1406. pathologically bad markup. It makes no assumptions about tag
  1407. nesting, but it does know which tags are self-closing, that
  1408. <script> tags contain Javascript and should not be parsed, that
  1409. META tags may contain encoding information, and so on.
  1410. This also makes it better for subclassing than BeautifulStoneSoup
  1411. or BeautifulSoup."""
  1412. RESET_NESTING_TAGS = buildTagMap('noscript')
  1413. NESTABLE_TAGS = {}
  1414. class BeautifulSOAP(BeautifulStoneSoup):
  1415. """This class will push a tag with only a single string child into
  1416. the tag's parent as an attribute. The attribute's name is the tag
  1417. name, and the value is the string child. An example should give
  1418. the flavor of the change:
  1419. <foo><bar>baz</bar></foo>
  1420. =>
  1421. <foo bar="baz"><bar>baz</bar></foo>
  1422. You can then access fooTag['bar'] instead of fooTag.barTag.string.
  1423. This is, of course, useful for scraping structures that tend to
  1424. use subelements instead of attributes, such as SOAP messages. Note
  1425. that it modifies its input, so don't print the modified version
  1426. out.
  1427. I'm not sure how many people really want to use this class; let me
  1428. know if you do. Mainly I like the name."""
  1429. def popTag(self):
  1430. if len(self.tagStack) > 1:
  1431. tag = self.tagStack[-1]
  1432. parent = self.tagStack[-2]
  1433. parent._getAttrMap()
  1434. if (isinstance(tag, Tag) and len(tag.contents) == 1 and
  1435. isinstance(tag.contents[0], NavigableString) and
  1436. not parent.attrMap.has_key(tag.name)):
  1437. parent[tag.name] = tag.contents[0]
  1438. BeautifulStoneSoup.popTag(self)
  1439. #Enterprise class names! It has come to our attention that some people
  1440. #think the names of the Beautiful Soup parser classes are too silly
  1441. #and "unprofessional" for use in enterprise screen-scraping. We feel
  1442. #your pain! For such-minded folk, the Beautiful Soup Consortium And
  1443. #All-Night Kosher Bakery recommends renaming this file to
  1444. #"RobustParser.py" (or, in cases of extreme enterprisiness,
  1445. #"RobustParserBeanInterface.class") and using the following
  1446. #enterprise-friendly class aliases:
  1447. class RobustXMLParser(BeautifulStoneSoup):
  1448. pass
  1449. class RobustHTMLParser(BeautifulSoup):
  1450. pass
  1451. class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup):
  1452. pass
  1453. class RobustInsanelyWackAssHTMLParser(MinimalSoup):
  1454. pass
  1455. class SimplifyingSOAPParser(BeautifulSOAP):
  1456. pass
  1457. ######################################################
  1458. #
  1459. # Bonus library: Unicode, Dammit
  1460. #
  1461. # This class forces XML data into a standard format (usually to UTF-8
  1462. # or Unicode). It is heavily based on code from Mark Pilgrim's
  1463. # Universal Feed Parser. It does not rewrite the XML or HTML to
  1464. # reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi
  1465. # (XML) and BeautifulSoup.start_meta (HTML).
  1466. # Autodetects character encodings.
  1467. # Download from http://chardet.feedparser.org/
  1468. try:
  1469. import chardet
  1470. # import chardet.constants
  1471. # chardet.constants._debug = 1
  1472. except ImportError:
  1473. chardet = None
  1474. # cjkcodecs and iconv_codec make Python know about more character encodings.
  1475. # Both are available from http://cjkpython.i18n.org/
  1476. # They're built in if you use Python 2.4.
  1477. try:
  1478. import cjkcodecs.aliases
  1479. except ImportError:
  1480. pass
  1481. try:
  1482. import iconv_codec
  1483. except ImportError:
  1484. pass
  1485. class UnicodeDammit:
  1486. """A class for detecting the encoding of a *ML document and
  1487. converting it to a Unicode string. If the source encoding is
  1488. windows-1252, can replace MS smart quotes with their HTML or XML
  1489. equivalents."""
  1490. # This dictionary maps commonly seen values for "charset" in HTML
  1491. # meta tags to the corresponding Python codec names. It only covers
  1492. # values that aren't in Python's aliases and can't be determined
  1493. # by the heuristics in find_codec.
  1494. CHARSET_ALIASES = { "macintosh" : "mac-roman",
  1495. "x-sjis" : "shift-jis" }
  1496. def __init__(self, markup, overrideEncodings=[],
  1497. smartQuotesTo='xml', isHTML=False):
  1498. self.declaredHTMLEncoding = None
  1499. self.markup, documentEncoding, sniffedEncoding = \
  1500. self._detectEncoding(markup, isHTML)
  1501. self.smartQuotesTo = smartQuotesTo
  1502. self.triedEncodings = []
  1503. if markup == '' or isinstance(markup, unicode):
  1504. self.originalEncoding = None
  1505. self.unicode = unicode(markup)
  1506. return
  1507. u = None
  1508. for proposedEncoding in overrideEncodings:
  1509. u = self._convertFrom(proposedEncoding)
  1510. if u: break
  1511. if not u:
  1512. for proposedEncoding in (documentEncoding, sniffedEncoding):
  1513. u = self._convertFrom(proposedEncoding)
  1514. if u: break
  1515. # If no luck and we have auto-detection library, try that:
  1516. if not u and chardet and not isinstance(self.markup, unicode):
  1517. u = self._convertFrom(chardet.detect(self.markup)['encoding'])
  1518. # As a last resort, try utf-8 and windows-1252:
  1519. if not u:
  1520. for proposed_encoding in ("utf-8", "windows-1252"):
  1521. u = self._convertFrom(proposed_encoding)
  1522. if u: break
  1523. self.unicode = u
  1524. if not u: self.originalEncoding = None
  1525. def _subMSChar(self, match):
  1526. """Changes a MS smart quote character to an XML or HTML
  1527. entity."""
  1528. orig = match.group(1)
  1529. sub = self.MS_CHARS.get(orig)
  1530. if type(sub) == types.TupleType:
  1531. if self.smartQuotesTo == 'xml':
  1532. sub = '&#x'.encode() + sub[1].encode() + ';'.encode()
  1533. else:
  1534. sub = '&'.encode() + sub[0].encode() + ';'.encode()
  1535. else:
  1536. sub = sub.encode()
  1537. return sub
  1538. def _convertFrom(self, proposed):
  1539. proposed = self.find_codec(proposed)
  1540. if not proposed or proposed in self.triedEncodings:
  1541. return None
  1542. self.triedEncodings.append(proposed)
  1543. markup = self.markup
  1544. # Convert smart quotes to HTML if coming from an encoding
  1545. # that might have them.
  1546. if self.smartQuotesTo and proposed.lower() in("windows-1252",
  1547. "iso-8859-1",
  1548. "iso-8859-2"):
  1549. # This implements the change in BeautifulSoup.py.3.diff
  1550. # that comes with BeautifulSoup.
  1551. smart_quotes_re = u"([\x80-\x9f])".encode('raw_unicode_escape')
  1552. smart_quotes_compiled = re.compile(smart_quotes_re)
  1553. markup = smart_quotes_compiled.sub(self._subMSChar, markup)
  1554. try:
  1555. # print "Trying to convert document to %s" % proposed
  1556. u = self._toUnicode(markup, proposed)
  1557. self.markup = u
  1558. self.originalEncoding = proposed
  1559. except Exception, e:
  1560. # print "That didn't work!"
  1561. # print e
  1562. return None
  1563. #print "Correct encoding: %s" % proposed
  1564. return self.markup
  1565. def _toUnicode(self, data, encoding):
  1566. '''Given a string and its encoding, decodes the string into Unicode.
  1567. %encoding is a string recognized by encodings.aliases'''
  1568. # strip Byte Order Mark (if present)
  1569. if (len(data) >= 4) and (data[:2] == '\xfe\xff') \
  1570. and (data[2:4] != '\x00\x00'):
  1571. encoding = 'utf-16be'
  1572. data = data[2:]
  1573. elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \
  1574. and (data[2:4] != '\x00\x00'):
  1575. encoding = 'utf-16le'
  1576. data = data[2:]
  1577. elif data[:3] == '\xef\xbb\xbf':
  1578. encoding = 'utf-8'
  1579. data = data[3:]
  1580. elif data[:4] == '\x00\x00\xfe\xff':
  1581. encoding = 'utf-32be'
  1582. data = data[4:]
  1583. elif data[:4] == '\xff\xfe\x00\x00':
  1584. encoding = 'utf-32le'
  1585. data = data[4:]
  1586. newdata = unicode(data, encoding)
  1587. return newdata
  1588. def _detectEncoding(self, xml_data, isHTML=False):
  1589. """Given a document, tries to detect its XML encoding."""
  1590. xml_encoding = sniffed_xml_encoding = None
  1591. try:
  1592. if xml_data[:4] == '\x4c\x6f\xa7\x94':
  1593. # EBCDIC
  1594. xml_data = self._ebcdic_to_ascii(xml_data)
  1595. elif xml_data[:4] == '\x00\x3c\x00\x3f':
  1596. # UTF-16BE
  1597. sniffed_xml_encoding = 'utf-16be'
  1598. xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
  1599. elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \
  1600. and (xml_data[2:4] != '\x00\x00'):
  1601. # UTF-16BE with BOM
  1602. sniffed_xml_encoding = 'utf-16be'
  1603. xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
  1604. elif xml_data[:4] == '\x3c\x00\x3f\x00':
  1605. # UTF-16LE
  1606. sniffed_xml_encoding = 'utf-16le'
  1607. xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
  1608. elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \
  1609. (xml_data[2:4] != '\x00\x00'):
  1610. # UTF-16LE with BOM
  1611. sniffed_xml_encoding = 'utf-16le'
  1612. xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
  1613. elif xml_data[:4] == '\x00\x00\x00\x3c':
  1614. # UTF-32BE
  1615. sniffed_xml_encoding = 'utf-32be'
  1616. xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
  1617. elif xml_data[:4] == '\x3c\x00\x00\x00':
  1618. # UTF-32LE
  1619. sniffed_xml_encoding = 'utf-32le'
  1620. xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
  1621. elif xml_data[:4] == '\x00\x00\xfe\xff':
  1622. # UTF-32BE with BOM
  1623. sniffed_xml_encoding = 'utf-32be'
  1624. xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
  1625. elif xml_data[:4] == '\xff\xfe\x00\x00':
  1626. # UTF-32LE with BOM
  1627. sniffed_xml_encoding = 'utf-32le'
  1628. xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
  1629. elif xml_data[:3] == '\xef\xbb\xbf':
  1630. # UTF-8 with BOM
  1631. sniffed_xml_encoding = 'utf-8'
  1632. xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
  1633. else:
  1634. sniffed_xml_encoding = 'ascii'
  1635. pass
  1636. except:
  1637. xml_encoding_match = None
  1638. xml_encoding_re = '^<\?.*encoding=[\'"](.*?)[\'"].*\?>'.encode()
  1639. xml_encoding_match = re.compile(xml_encoding_re).match(xml_data)
  1640. if not xml_encoding_match and isHTML:
  1641. meta_re = '<\s*meta[^>]+charset=([^>]*?)[;\'">]'.encode()
  1642. regexp = re.compile(meta_re, re.I)
  1643. xml_encoding_match = regexp.search(xml_data)
  1644. if xml_encoding_match is not None:
  1645. xml_encoding = xml_encoding_match.groups()[0].decode(
  1646. 'ascii').lower()
  1647. if isHTML:
  1648. self.declaredHTMLEncoding = xml_encoding
  1649. if sniffed_xml_encoding and \
  1650. (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',
  1651. 'iso-10646-ucs-4', 'ucs-4', 'csucs4',
  1652. 'utf-16', 'utf-32', 'utf_16', 'utf_32',
  1653. 'utf16', 'u16')):
  1654. xml_encoding = sniffed_xml_encoding
  1655. return xml_data, xml_encoding, sniffed_xml_encoding
  1656. def find_codec(self, charset):
  1657. return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \
  1658. or (charset and self._codec(charset.replace("-", ""))) \
  1659. or (charset and self._codec(charset.replace("-", "_"))) \
  1660. or charset
  1661. def _codec(self, charset):
  1662. if not charset: return charset
  1663. codec = None
  1664. try:
  1665. codecs.lookup(charset)
  1666. codec = charset
  1667. except (LookupError, ValueError):
  1668. pass
  1669. return codec
  1670. EBCDIC_TO_ASCII_MAP = None
  1671. def _ebcdic_to_ascii(self, s):
  1672. c = self.__class__
  1673. if not c.EBCDIC_TO_ASCII_MAP:
  1674. emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
  1675. 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
  1676. 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
  1677. 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
  1678. 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
  1679. 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
  1680. 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
  1681. 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
  1682. 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,
  1683. 201,202,106,107,108,109,110,111,112,113,114,203,204,205,
  1684. 206,207,208,209,126,115,116,117,118,119,120,121,122,210,
  1685. 211,212,213,214,215,216,217,218,219,220,221,222,223,224,
  1686. 225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72,
  1687. 73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81,
  1688. 82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89,
  1689. 90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57,
  1690. 250,251,252,253,254,255)
  1691. import string
  1692. c.EBCDIC_TO_ASCII_MAP = string.maketrans( \
  1693. ''.join(map(chr, range(256))), ''.join(map(chr, emap)))
  1694. return s.translate(c.EBCDIC_TO_ASCII_MAP)
  1695. MS_CHARS = { '\x80' : ('euro', '20AC'),
  1696. '\x81' : ' ',
  1697. '\x82' : ('sbquo', '201A'),
  1698. '\x83' : ('fnof', '192'),
  1699. '\x84' : ('bdquo', '201E'),
  1700. '\x85' : ('hellip', '2026'),
  1701. '\x86' : ('dagger', '2020'),
  1702. '\x87' : ('Dagger', '2021'),
  1703. '\x88' : ('circ', '2C6'),
  1704. '\x89' : ('permil', '2030'),
  1705. '\x8A' : ('Scaron', '160'),
  1706. '\x8B' : ('lsaquo', '2039'),
  1707. '\x8C' : ('OElig', '152'),
  1708. '\x8D' : '?',
  1709. '\x8E' : ('#x17D', '17D'),
  1710. '\x8F' : '?',
  1711. '\x90' : '?',
  1712. '\x91' : ('lsquo', '2018'),
  1713. '\x92' : ('rsquo', '2019'),
  1714. '\x93' : ('ldquo', '201C'),
  1715. '\x94' : ('rdquo', '201D'),
  1716. '\x95' : ('bull', '2022'),
  1717. '\x96' : ('ndash', '2013'),
  1718. '\x97' : ('mdash', '2014'),
  1719. '\x98' : ('tilde', '2DC'),
  1720. '\x99' : ('trade', '2122'),
  1721. '\x9a' : ('scaron', '161'),
  1722. '\x9b' : ('rsaquo', '203A'),
  1723. '\x9c' : ('oelig', '153'),
  1724. '\x9d' : '?',
  1725. '\x9e' : ('#x17E', '17E'),
  1726. '\x9f' : ('Yuml', ''),}
  1727. # This implements the change in the BeautifulSoup.py.3.diff file
  1728. # that comes with BeautifulSoup.
  1729. if sys.version_info[0] >= 3:
  1730. replace = {}
  1731. for key in MS_CHARS:
  1732. replace[key.encode('raw_unicode_escape')] = MS_CHARS[key]
  1733. MS_CHARS = replace
  1734. #######################################################################
  1735. #By default, act as an HTML pretty-printer.
  1736. if __name__ == '__main__':
  1737. import sys
  1738. soup = BeautifulSoup(sys.stdin)
  1739. print soup.prettify()