PageRenderTime 31ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/BeautifulSoup.py

https://bitbucket.org/hgulldahl/liksapp
Python | 1965 lines | 1829 code | 60 blank | 76 comment | 98 complexity | f550d3ac881763aff904b2718780aeb5 MD5 | raw file
  1. """Beautiful Soup
  2. Elixir and Tonic
  3. "The Screen-Scraper's Friend"
  4. http://www.crummy.com/software/BeautifulSoup/
  5. Beautiful Soup parses a (possibly invalid) XML or HTML document into a
  6. tree representation. It provides methods and Pythonic idioms that make
  7. it easy to navigate, search, and modify the tree.
  8. A well-formed XML/HTML document yields a well-formed data
  9. structure. An ill-formed XML/HTML document yields a correspondingly
  10. ill-formed data structure. If your document is only locally
  11. well-formed, you can use this library to find and process the
  12. well-formed part of it.
  13. Beautiful Soup works with Python 2.2 and up. It has no external
  14. dependencies, but you'll have more success at converting data to UTF-8
  15. if you also install these three packages:
  16. * chardet, for auto-detecting character encodings
  17. http://chardet.feedparser.org/
  18. * cjkcodecs and iconv_codec, which add more encodings to the ones supported
  19. by stock Python.
  20. http://cjkpython.i18n.org/
  21. Beautiful Soup defines classes for two main parsing strategies:
  22. * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific
  23. language that kind of looks like XML.
  24. * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid
  25. or invalid. This class has web browser-like heuristics for
  26. obtaining a sensible parse tree in the face of common HTML errors.
  27. Beautiful Soup also defines a class (UnicodeDammit) for autodetecting
  28. the encoding of an HTML or XML document, and converting it to
  29. Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser.
  30. For more than you ever wanted to know about Beautiful Soup, see the
  31. documentation:
  32. http://www.crummy.com/software/BeautifulSoup/documentation.html
  33. Here, have some legalese:
  34. Copyright (c) 2004-2008, Leonard Richardson
  35. All rights reserved.
  36. Redistribution and use in source and binary forms, with or without
  37. modification, are permitted provided that the following conditions are
  38. met:
  39. * Redistributions of source code must retain the above copyright
  40. notice, this list of conditions and the following disclaimer.
  41. * Redistributions in binary form must reproduce the above
  42. copyright notice, this list of conditions and the following
  43. disclaimer in the documentation and/or other materials provided
  44. with the distribution.
  45. * Neither the name of the the Beautiful Soup Consortium and All
  46. Night Kosher Bakery nor the names of its contributors may be
  47. used to endorse or promote products derived from this software
  48. without specific prior written permission.
  49. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  50. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  51. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  52. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  53. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  54. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  55. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  56. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  57. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  58. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  59. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT.
  60. """
  61. from __future__ import generators
  62. __author__ = "Leonard Richardson (leonardr@segfault.org)"
  63. __version__ = "3.0.7a"
  64. __copyright__ = "Copyright (c) 2004-2008 Leonard Richardson"
  65. __license__ = "New-style BSD"
  66. from sgmllib import SGMLParser, SGMLParseError
  67. import codecs
  68. import markupbase
  69. import types
  70. import re
  71. import sgmllib
  72. try:
  73. from htmlentitydefs import name2codepoint
  74. except ImportError:
  75. name2codepoint = {}
  76. try:
  77. set
  78. except NameError:
  79. from sets import Set as set
  80. #These hacks make Beautiful Soup able to parse XML with namespaces
  81. sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
  82. markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match
  83. DEFAULT_OUTPUT_ENCODING = "utf-8"
  84. # First, the classes that represent markup elements.
  85. class PageElement:
  86. """Contains the navigational information for some part of the page
  87. (either a tag or a piece of text)"""
  88. def setup(self, parent=None, previous=None):
  89. """Sets up the initial relations between this element and
  90. other elements."""
  91. self.parent = parent
  92. self.previous = previous
  93. self.next = None
  94. self.previousSibling = None
  95. self.nextSibling = None
  96. if self.parent and self.parent.contents:
  97. self.previousSibling = self.parent.contents[-1]
  98. self.previousSibling.nextSibling = self
  99. def replaceWith(self, replaceWith):
  100. oldParent = self.parent
  101. myIndex = self.parent.contents.index(self)
  102. if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent:
  103. # We're replacing this element with one of its siblings.
  104. index = self.parent.contents.index(replaceWith)
  105. if index and index < myIndex:
  106. # Furthermore, it comes before this element. That
  107. # means that when we extract it, the index of this
  108. # element will change.
  109. myIndex = myIndex - 1
  110. self.extract()
  111. oldParent.insert(myIndex, replaceWith)
  112. def extract(self):
  113. """Destructively rips this element out of the tree."""
  114. if self.parent:
  115. try:
  116. self.parent.contents.remove(self)
  117. except ValueError:
  118. pass
  119. #Find the two elements that would be next to each other if
  120. #this element (and any children) hadn't been parsed. Connect
  121. #the two.
  122. lastChild = self._lastRecursiveChild()
  123. nextElement = lastChild.next
  124. if self.previous:
  125. self.previous.next = nextElement
  126. if nextElement:
  127. nextElement.previous = self.previous
  128. self.previous = None
  129. lastChild.next = None
  130. self.parent = None
  131. if self.previousSibling:
  132. self.previousSibling.nextSibling = self.nextSibling
  133. if self.nextSibling:
  134. self.nextSibling.previousSibling = self.previousSibling
  135. self.previousSibling = self.nextSibling = None
  136. return self
  137. def _lastRecursiveChild(self):
  138. "Finds the last element beneath this object to be parsed."
  139. lastChild = self
  140. while hasattr(lastChild, 'contents') and lastChild.contents:
  141. lastChild = lastChild.contents[-1]
  142. return lastChild
  143. def insert(self, position, newChild):
  144. if (isinstance(newChild, basestring)
  145. or isinstance(newChild, unicode)) \
  146. and not isinstance(newChild, NavigableString):
  147. newChild = NavigableString(newChild)
  148. position = min(position, len(self.contents))
  149. if hasattr(newChild, 'parent') and newChild.parent != None:
  150. # We're 'inserting' an element that's already one
  151. # of this object's children.
  152. if newChild.parent == self:
  153. index = self.find(newChild)
  154. if index and index < position:
  155. # Furthermore we're moving it further down the
  156. # list of this object's children. That means that
  157. # when we extract this element, our target index
  158. # will jump down one.
  159. position = position - 1
  160. newChild.extract()
  161. newChild.parent = self
  162. previousChild = None
  163. if position == 0:
  164. newChild.previousSibling = None
  165. newChild.previous = self
  166. else:
  167. previousChild = self.contents[position-1]
  168. newChild.previousSibling = previousChild
  169. newChild.previousSibling.nextSibling = newChild
  170. newChild.previous = previousChild._lastRecursiveChild()
  171. if newChild.previous:
  172. newChild.previous.next = newChild
  173. newChildsLastElement = newChild._lastRecursiveChild()
  174. if position >= len(self.contents):
  175. newChild.nextSibling = None
  176. parent = self
  177. parentsNextSibling = None
  178. while not parentsNextSibling:
  179. parentsNextSibling = parent.nextSibling
  180. parent = parent.parent
  181. if not parent: # This is the last element in the document.
  182. break
  183. if parentsNextSibling:
  184. newChildsLastElement.next = parentsNextSibling
  185. else:
  186. newChildsLastElement.next = None
  187. else:
  188. nextChild = self.contents[position]
  189. newChild.nextSibling = nextChild
  190. if newChild.nextSibling:
  191. newChild.nextSibling.previousSibling = newChild
  192. newChildsLastElement.next = nextChild
  193. if newChildsLastElement.next:
  194. newChildsLastElement.next.previous = newChildsLastElement
  195. self.contents.insert(position, newChild)
  196. def append(self, tag):
  197. """Appends the given tag to the contents of this tag."""
  198. self.insert(len(self.contents), tag)
  199. def findNext(self, name=None, attrs={}, text=None, **kwargs):
  200. """Returns the first item that matches the given criteria and
  201. appears after this Tag in the document."""
  202. return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
  203. def findAllNext(self, name=None, attrs={}, text=None, limit=None,
  204. **kwargs):
  205. """Returns all items that match the given criteria and appear
  206. after this Tag in the document."""
  207. return self._findAll(name, attrs, text, limit, self.nextGenerator,
  208. **kwargs)
  209. def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
  210. """Returns the closest sibling to this Tag that matches the
  211. given criteria and appears after this Tag in the document."""
  212. return self._findOne(self.findNextSiblings, name, attrs, text,
  213. **kwargs)
  214. def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,
  215. **kwargs):
  216. """Returns the siblings of this Tag that match the given
  217. criteria and appear after this Tag in the document."""
  218. return self._findAll(name, attrs, text, limit,
  219. self.nextSiblingGenerator, **kwargs)
  220. fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x
  221. def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
  222. """Returns the first item that matches the given criteria and
  223. appears before this Tag in the document."""
  224. return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
  225. def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,
  226. **kwargs):
  227. """Returns all items that match the given criteria and appear
  228. before this Tag in the document."""
  229. return self._findAll(name, attrs, text, limit, self.previousGenerator,
  230. **kwargs)
  231. fetchPrevious = findAllPrevious # Compatibility with pre-3.x
  232. def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
  233. """Returns the closest sibling to this Tag that matches the
  234. given criteria and appears before this Tag in the document."""
  235. return self._findOne(self.findPreviousSiblings, name, attrs, text,
  236. **kwargs)
  237. def findPreviousSiblings(self, name=None, attrs={}, text=None,
  238. limit=None, **kwargs):
  239. """Returns the siblings of this Tag that match the given
  240. criteria and appear before this Tag in the document."""
  241. return self._findAll(name, attrs, text, limit,
  242. self.previousSiblingGenerator, **kwargs)
  243. fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x
  244. def findParent(self, name=None, attrs={}, **kwargs):
  245. """Returns the closest parent of this Tag that matches the given
  246. criteria."""
  247. # NOTE: We can't use _findOne because findParents takes a different
  248. # set of arguments.
  249. r = None
  250. l = self.findParents(name, attrs, 1)
  251. if l:
  252. r = l[0]
  253. return r
  254. def findParents(self, name=None, attrs={}, limit=None, **kwargs):
  255. """Returns the parents of this Tag that match the given
  256. criteria."""
  257. return self._findAll(name, attrs, None, limit, self.parentGenerator,
  258. **kwargs)
  259. fetchParents = findParents # Compatibility with pre-3.x
  260. #These methods do the real heavy lifting.
  261. def _findOne(self, method, name, attrs, text, **kwargs):
  262. r = None
  263. l = method(name, attrs, text, 1, **kwargs)
  264. if l:
  265. r = l[0]
  266. return r
  267. def _findAll(self, name, attrs, text, limit, generator, **kwargs):
  268. "Iterates over a generator looking for things that match."
  269. if isinstance(name, SoupStrainer):
  270. strainer = name
  271. else:
  272. # Build a SoupStrainer
  273. strainer = SoupStrainer(name, attrs, text, **kwargs)
  274. results = ResultSet(strainer)
  275. g = generator()
  276. while True:
  277. try:
  278. i = g.next()
  279. except StopIteration:
  280. break
  281. if i:
  282. found = strainer.search(i)
  283. if found:
  284. results.append(found)
  285. if limit and len(results) >= limit:
  286. break
  287. return results
  288. #These Generators can be used to navigate starting from both
  289. #NavigableStrings and Tags.
  290. def nextGenerator(self):
  291. i = self
  292. while i:
  293. i = i.next
  294. yield i
  295. def nextSiblingGenerator(self):
  296. i = self
  297. while i:
  298. i = i.nextSibling
  299. yield i
  300. def previousGenerator(self):
  301. i = self
  302. while i:
  303. i = i.previous
  304. yield i
  305. def previousSiblingGenerator(self):
  306. i = self
  307. while i:
  308. i = i.previousSibling
  309. yield i
  310. def parentGenerator(self):
  311. i = self
  312. while i:
  313. i = i.parent
  314. yield i
  315. # Utility methods
  316. def substituteEncoding(self, str, encoding=None):
  317. encoding = encoding or "utf-8"
  318. return str.replace("%SOUP-ENCODING%", encoding)
  319. def toEncoding(self, s, encoding=None):
  320. """Encodes an object to a string in some encoding, or to Unicode.
  321. ."""
  322. if isinstance(s, unicode):
  323. if encoding:
  324. s = s.encode(encoding)
  325. elif isinstance(s, str):
  326. if encoding:
  327. s = s.encode(encoding)
  328. else:
  329. s = unicode(s)
  330. else:
  331. if encoding:
  332. s = self.toEncoding(str(s), encoding)
  333. else:
  334. s = unicode(s)
  335. return s
  336. class NavigableString(unicode, PageElement):
  337. def __new__(cls, value):
  338. """Create a new NavigableString.
  339. When unpickling a NavigableString, this method is called with
  340. the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
  341. passed in to the superclass's __new__ or the superclass won't know
  342. how to handle non-ASCII characters.
  343. """
  344. if isinstance(value, unicode):
  345. return unicode.__new__(cls, value)
  346. return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
  347. def __getnewargs__(self):
  348. return (NavigableString.__str__(self),)
  349. def __getattr__(self, attr):
  350. """text.string gives you text. This is for backwards
  351. compatibility for Navigable*String, but for CData* it lets you
  352. get the string without the CData wrapper."""
  353. if attr == 'string':
  354. return self
  355. else:
  356. raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
  357. def __unicode__(self):
  358. return str(self).decode(DEFAULT_OUTPUT_ENCODING)
  359. def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  360. if encoding:
  361. return self.encode(encoding)
  362. else:
  363. return self
  364. class CData(NavigableString):
  365. def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  366. return "<![CDATA[%s]]>" % NavigableString.__str__(self, encoding)
  367. class ProcessingInstruction(NavigableString):
  368. def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  369. output = self
  370. if "%SOUP-ENCODING%" in output:
  371. output = self.substituteEncoding(output, encoding)
  372. return "<?%s?>" % self.toEncoding(output, encoding)
  373. class Comment(NavigableString):
  374. def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  375. return "<!--%s-->" % NavigableString.__str__(self, encoding)
  376. class Declaration(NavigableString):
  377. def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  378. return "<!%s>" % NavigableString.__str__(self, encoding)
  379. class Tag(PageElement):
  380. """Represents a found HTML tag with its attributes and contents."""
  381. def _invert(h):
  382. "Cheap function to invert a hash."
  383. i = {}
  384. for k,v in h.items():
  385. i[v] = k
  386. return i
  387. XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'",
  388. "quot" : '"',
  389. "amp" : "&",
  390. "lt" : "<",
  391. "gt" : ">" }
  392. XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS)
  393. def _convertEntities(self, match):
  394. """Used in a call to re.sub to replace HTML, XML, and numeric
  395. entities with the appropriate Unicode characters. If HTML
  396. entities are being converted, any unrecognized entities are
  397. escaped."""
  398. x = match.group(1)
  399. if self.convertHTMLEntities and x in name2codepoint:
  400. return unichr(name2codepoint[x])
  401. elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS:
  402. if self.convertXMLEntities:
  403. return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]
  404. else:
  405. return u'&%s;' % x
  406. elif len(x) > 0 and x[0] == '#':
  407. # Handle numeric entities
  408. if len(x) > 1 and x[1] == 'x':
  409. return unichr(int(x[2:], 16))
  410. else:
  411. return unichr(int(x[1:]))
  412. elif self.escapeUnrecognizedEntities:
  413. return u'&amp;%s;' % x
  414. else:
  415. return u'&%s;' % x
  416. def __init__(self, parser, name, attrs=None, parent=None,
  417. previous=None):
  418. "Basic constructor."
  419. # We don't actually store the parser object: that lets extracted
  420. # chunks be garbage-collected
  421. self.parserClass = parser.__class__
  422. self.isSelfClosing = parser.isSelfClosingTag(name)
  423. self.name = name
  424. if attrs == None:
  425. attrs = []
  426. self.attrs = attrs
  427. self.contents = []
  428. self.setup(parent, previous)
  429. self.hidden = False
  430. self.containsSubstitutions = False
  431. self.convertHTMLEntities = parser.convertHTMLEntities
  432. self.convertXMLEntities = parser.convertXMLEntities
  433. self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
  434. # Convert any HTML, XML, or numeric entities in the attribute values.
  435. convert = lambda(k, val): (k,
  436. re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);",
  437. self._convertEntities,
  438. val))
  439. self.attrs = map(convert, self.attrs)
  440. def get(self, key, default=None):
  441. """Returns the value of the 'key' attribute for the tag, or
  442. the value given for 'default' if it doesn't have that
  443. attribute."""
  444. return self._getAttrMap().get(key, default)
  445. def has_key(self, key):
  446. return self._getAttrMap().has_key(key)
  447. def __getitem__(self, key):
  448. """tag[key] returns the value of the 'key' attribute for the tag,
  449. and throws an exception if it's not there."""
  450. return self._getAttrMap()[key]
  451. def __iter__(self):
  452. "Iterating over a tag iterates over its contents."
  453. return iter(self.contents)
  454. def __len__(self):
  455. "The length of a tag is the length of its list of contents."
  456. return len(self.contents)
  457. def __contains__(self, x):
  458. return x in self.contents
  459. def __nonzero__(self):
  460. "A tag is non-None even if it has no contents."
  461. return True
  462. def __setitem__(self, key, value):
  463. """Setting tag[key] sets the value of the 'key' attribute for the
  464. tag."""
  465. self._getAttrMap()
  466. self.attrMap[key] = value
  467. found = False
  468. for i in range(0, len(self.attrs)):
  469. if self.attrs[i][0] == key:
  470. self.attrs[i] = (key, value)
  471. found = True
  472. if not found:
  473. self.attrs.append((key, value))
  474. self._getAttrMap()[key] = value
  475. def __delitem__(self, key):
  476. "Deleting tag[key] deletes all 'key' attributes for the tag."
  477. for item in self.attrs:
  478. if item[0] == key:
  479. self.attrs.remove(item)
  480. #We don't break because bad HTML can define the same
  481. #attribute multiple times.
  482. self._getAttrMap()
  483. if self.attrMap.has_key(key):
  484. del self.attrMap[key]
  485. def __call__(self, *args, **kwargs):
  486. """Calling a tag like a function is the same as calling its
  487. findAll() method. Eg. tag('a') returns a list of all the A tags
  488. found within this tag."""
  489. return apply(self.findAll, args, kwargs)
  490. def __getattr__(self, tag):
  491. #print "Getattr %s.%s" % (self.__class__, tag)
  492. if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3:
  493. return self.find(tag[:-3])
  494. elif tag.find('__') != 0:
  495. return self.find(tag)
  496. raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag)
  497. def __eq__(self, other):
  498. """Returns true iff this tag has the same name, the same attributes,
  499. and the same contents (recursively) as the given tag.
  500. NOTE: right now this will return false if two tags have the
  501. same attributes in a different order. Should this be fixed?"""
  502. if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other):
  503. return False
  504. for i in range(0, len(self.contents)):
  505. if self.contents[i] != other.contents[i]:
  506. return False
  507. return True
  508. def __ne__(self, other):
  509. """Returns true iff this tag is not identical to the other tag,
  510. as defined in __eq__."""
  511. return not self == other
  512. def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  513. """Renders this tag as a string."""
  514. return self.__str__(encoding)
  515. def __unicode__(self):
  516. return self.__str__(None)
  517. BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|"
  518. + "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)"
  519. + ")")
  520. def _sub_entity(self, x):
  521. """Used with a regular expression to substitute the
  522. appropriate XML entity for an XML special character."""
  523. return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";"
  524. def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING,
  525. prettyPrint=False, indentLevel=0):
  526. """Returns a string or Unicode representation of this tag and
  527. its contents. To get Unicode, pass None for encoding.
  528. NOTE: since Python's HTML parser consumes whitespace, this
  529. method is not certain to reproduce the whitespace present in
  530. the original string."""
  531. encodedName = self.toEncoding(self.name, encoding)
  532. attrs = []
  533. if self.attrs:
  534. for key, val in self.attrs:
  535. fmt = '%s="%s"'
  536. if isString(val):
  537. if self.containsSubstitutions and '%SOUP-ENCODING%' in val:
  538. val = self.substituteEncoding(val, encoding)
  539. # The attribute value either:
  540. #
  541. # * Contains no embedded double quotes or single quotes.
  542. # No problem: we enclose it in double quotes.
  543. # * Contains embedded single quotes. No problem:
  544. # double quotes work here too.
  545. # * Contains embedded double quotes. No problem:
  546. # we enclose it in single quotes.
  547. # * Embeds both single _and_ double quotes. This
  548. # can't happen naturally, but it can happen if
  549. # you modify an attribute value after parsing
  550. # the document. Now we have a bit of a
  551. # problem. We solve it by enclosing the
  552. # attribute in single quotes, and escaping any
  553. # embedded single quotes to XML entities.
  554. if '"' in val:
  555. fmt = "%s='%s'"
  556. if "'" in val:
  557. # TODO: replace with apos when
  558. # appropriate.
  559. val = val.replace("'", "&squot;")
  560. # Now we're okay w/r/t quotes. But the attribute
  561. # value might also contain angle brackets, or
  562. # ampersands that aren't part of entities. We need
  563. # to escape those to XML entities too.
  564. val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val)
  565. attrs.append(fmt % (self.toEncoding(key, encoding),
  566. self.toEncoding(val, encoding)))
  567. close = ''
  568. closeTag = ''
  569. if self.isSelfClosing:
  570. close = ' /'
  571. else:
  572. closeTag = '</%s>' % encodedName
  573. indentTag, indentContents = 0, 0
  574. if prettyPrint:
  575. indentTag = indentLevel
  576. space = (' ' * (indentTag-1))
  577. indentContents = indentTag + 1
  578. contents = self.renderContents(encoding, prettyPrint, indentContents)
  579. if self.hidden:
  580. s = contents
  581. else:
  582. s = []
  583. attributeString = ''
  584. if attrs:
  585. attributeString = ' ' + ' '.join(attrs)
  586. if prettyPrint:
  587. s.append(space)
  588. s.append('<%s%s%s>' % (encodedName, attributeString, close))
  589. if prettyPrint:
  590. s.append("\n")
  591. s.append(contents)
  592. if prettyPrint and contents and contents[-1] != "\n":
  593. s.append("\n")
  594. if prettyPrint and closeTag:
  595. s.append(space)
  596. s.append(closeTag)
  597. if prettyPrint and closeTag and self.nextSibling:
  598. s.append("\n")
  599. s = ''.join(s)
  600. return s
  601. def decompose(self):
  602. """Recursively destroys the contents of this tree."""
  603. contents = [i for i in self.contents]
  604. for i in contents:
  605. if isinstance(i, Tag):
  606. i.decompose()
  607. else:
  608. i.extract()
  609. self.extract()
  610. def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING):
  611. return self.__str__(encoding, True)
  612. def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
  613. prettyPrint=False, indentLevel=0):
  614. """Renders the contents of this tag as a string in the given
  615. encoding. If encoding is None, returns a Unicode string.."""
  616. s=[]
  617. for c in self:
  618. text = None
  619. if isinstance(c, NavigableString):
  620. text = c.__str__(encoding)
  621. elif isinstance(c, Tag):
  622. s.append(c.__str__(encoding, prettyPrint, indentLevel))
  623. if text and prettyPrint:
  624. text = text.strip()
  625. if text:
  626. if prettyPrint:
  627. s.append(" " * (indentLevel-1))
  628. s.append(text)
  629. if prettyPrint:
  630. s.append("\n")
  631. return ''.join(s)
  632. #Soup methods
  633. def find(self, name=None, attrs={}, recursive=True, text=None,
  634. **kwargs):
  635. """Return only the first child of this Tag matching the given
  636. criteria."""
  637. r = None
  638. l = self.findAll(name, attrs, recursive, text, 1, **kwargs)
  639. if l:
  640. r = l[0]
  641. return r
  642. findChild = find
  643. def findAll(self, name=None, attrs={}, recursive=True, text=None,
  644. limit=None, **kwargs):
  645. """Extracts a list of Tag objects that match the given
  646. criteria. You can specify the name of the Tag and any
  647. attributes you want the Tag to have.
  648. The value of a key-value pair in the 'attrs' map can be a
  649. string, a list of strings, a regular expression object, or a
  650. callable that takes a string and returns whether or not the
  651. string matches for some custom definition of 'matches'. The
  652. same is true of the tag name."""
  653. generator = self.recursiveChildGenerator
  654. if not recursive:
  655. generator = self.childGenerator
  656. return self._findAll(name, attrs, text, limit, generator, **kwargs)
  657. findChildren = findAll
  658. # Pre-3.x compatibility methods
  659. first = find
  660. fetch = findAll
  661. def fetchText(self, text=None, recursive=True, limit=None):
  662. return self.findAll(text=text, recursive=recursive, limit=limit)
  663. def firstText(self, text=None, recursive=True):
  664. return self.find(text=text, recursive=recursive)
  665. #Private methods
  666. def _getAttrMap(self):
  667. """Initializes a map representation of this tag's attributes,
  668. if not already initialized."""
  669. if not getattr(self, 'attrMap'):
  670. self.attrMap = {}
  671. for (key, value) in self.attrs:
  672. self.attrMap[key] = value
  673. return self.attrMap
  674. #Generator methods
  675. def childGenerator(self):
  676. for i in range(0, len(self.contents)):
  677. yield self.contents[i]
  678. raise StopIteration
  679. def recursiveChildGenerator(self):
  680. stack = [(self, 0)]
  681. while stack:
  682. tag, start = stack.pop()
  683. if isinstance(tag, Tag):
  684. for i in range(start, len(tag.contents)):
  685. a = tag.contents[i]
  686. yield a
  687. if isinstance(a, Tag) and tag.contents:
  688. if i < len(tag.contents) - 1:
  689. stack.append((tag, i+1))
  690. stack.append((a, 0))
  691. break
  692. raise StopIteration
  693. # Next, a couple classes to represent queries and their results.
  694. class SoupStrainer:
  695. """Encapsulates a number of ways of matching a markup element (tag or
  696. text)."""
  697. def __init__(self, name=None, attrs={}, text=None, **kwargs):
  698. self.name = name
  699. if isString(attrs):
  700. kwargs['class'] = attrs
  701. attrs = None
  702. if kwargs:
  703. if attrs:
  704. attrs = attrs.copy()
  705. attrs.update(kwargs)
  706. else:
  707. attrs = kwargs
  708. self.attrs = attrs
  709. self.text = text
  710. def __str__(self):
  711. if self.text:
  712. return self.text
  713. else:
  714. return "%s|%s" % (self.name, self.attrs)
  715. def searchTag(self, markupName=None, markupAttrs={}):
  716. found = None
  717. markup = None
  718. if isinstance(markupName, Tag):
  719. markup = markupName
  720. markupAttrs = markup
  721. callFunctionWithTagData = callable(self.name) \
  722. and not isinstance(markupName, Tag)
  723. if (not self.name) \
  724. or callFunctionWithTagData \
  725. or (markup and self._matches(markup, self.name)) \
  726. or (not markup and self._matches(markupName, self.name)):
  727. if callFunctionWithTagData:
  728. match = self.name(markupName, markupAttrs)
  729. else:
  730. match = True
  731. markupAttrMap = None
  732. for attr, matchAgainst in self.attrs.items():
  733. if not markupAttrMap:
  734. if hasattr(markupAttrs, 'get'):
  735. markupAttrMap = markupAttrs
  736. else:
  737. markupAttrMap = {}
  738. for k,v in markupAttrs:
  739. markupAttrMap[k] = v
  740. attrValue = markupAttrMap.get(attr)
  741. if not self._matches(attrValue, matchAgainst):
  742. match = False
  743. break
  744. if match:
  745. if markup:
  746. found = markup
  747. else:
  748. found = markupName
  749. return found
  750. def search(self, markup):
  751. #print 'looking for %s in %s' % (self, markup)
  752. found = None
  753. # If given a list of items, scan it for a text element that
  754. # matches.
  755. if isList(markup) and not isinstance(markup, Tag):
  756. for element in markup:
  757. if isinstance(element, NavigableString) \
  758. and self.search(element):
  759. found = element
  760. break
  761. # If it's a Tag, make sure its name or attributes match.
  762. # Don't bother with Tags if we're searching for text.
  763. elif isinstance(markup, Tag):
  764. if not self.text:
  765. found = self.searchTag(markup)
  766. # If it's text, make sure the text matches.
  767. elif isinstance(markup, NavigableString) or \
  768. isString(markup):
  769. if self._matches(markup, self.text):
  770. found = markup
  771. else:
  772. raise Exception, "I don't know how to match against a %s" \
  773. % markup.__class__
  774. return found
  775. def _matches(self, markup, matchAgainst):
  776. #print "Matching %s against %s" % (markup, matchAgainst)
  777. result = False
  778. if matchAgainst == True and type(matchAgainst) == types.BooleanType:
  779. result = markup != None
  780. elif callable(matchAgainst):
  781. result = matchAgainst(markup)
  782. else:
  783. #Custom match methods take the tag as an argument, but all
  784. #other ways of matching match the tag name as a string.
  785. if isinstance(markup, Tag):
  786. markup = markup.name
  787. if markup and not isString(markup):
  788. markup = unicode(markup)
  789. #Now we know that chunk is either a string, or None.
  790. if hasattr(matchAgainst, 'match'):
  791. # It's a regexp object.
  792. result = markup and matchAgainst.search(markup)
  793. elif isList(matchAgainst):
  794. result = markup in matchAgainst
  795. elif hasattr(matchAgainst, 'items'):
  796. result = markup.has_key(matchAgainst)
  797. elif matchAgainst and isString(markup):
  798. if isinstance(markup, unicode):
  799. matchAgainst = unicode(matchAgainst)
  800. else:
  801. matchAgainst = str(matchAgainst)
  802. if not result:
  803. result = matchAgainst == markup
  804. return result
  805. class ResultSet(list):
  806. """A ResultSet is just a list that keeps track of the SoupStrainer
  807. that created it."""
  808. def __init__(self, source):
  809. list.__init__([])
  810. self.source = source
  811. # Now, some helper functions.
  812. def isList(l):
  813. """Convenience method that works with all 2.x versions of Python
  814. to determine whether or not something is listlike."""
  815. return hasattr(l, '__iter__') \
  816. or (type(l) in (types.ListType, types.TupleType))
  817. def isString(s):
  818. """Convenience method that works with all 2.x versions of Python
  819. to determine whether or not something is stringlike."""
  820. try:
  821. return isinstance(s, unicode) or isinstance(s, basestring)
  822. except NameError:
  823. return isinstance(s, str)
  824. def buildTagMap(default, *args):
  825. """Turns a list of maps, lists, or scalars into a single map.
  826. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and
  827. NESTING_RESET_TAGS maps out of lists and partial maps."""
  828. built = {}
  829. for portion in args:
  830. if hasattr(portion, 'items'):
  831. #It's a map. Merge it.
  832. for k,v in portion.items():
  833. built[k] = v
  834. elif isList(portion):
  835. #It's a list. Map each item to the default.
  836. for k in portion:
  837. built[k] = default
  838. else:
  839. #It's a scalar. Map it to the default.
  840. built[portion] = default
  841. return built
  842. # Now, the parser classes.
  843. class BeautifulStoneSoup(Tag, SGMLParser):
  844. """This class contains the basic parser and search code. It defines
  845. a parser that knows nothing about tag behavior except for the
  846. following:
  847. You can't close a tag without closing all the tags it encloses.
  848. That is, "<foo><bar></foo>" actually means
  849. "<foo><bar></bar></foo>".
  850. [Another possible explanation is "<foo><bar /></foo>", but since
  851. this class defines no SELF_CLOSING_TAGS, it will never use that
  852. explanation.]
  853. This class is useful for parsing XML or made-up markup languages,
  854. or when BeautifulSoup makes an assumption counter to what you were
  855. expecting."""
  856. SELF_CLOSING_TAGS = {}
  857. NESTABLE_TAGS = {}
  858. RESET_NESTING_TAGS = {}
  859. QUOTE_TAGS = {}
  860. PRESERVE_WHITESPACE_TAGS = []
  861. MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'),
  862. lambda x: x.group(1) + ' />'),
  863. (re.compile('<!\s+([^<>]*)>'),
  864. lambda x: '<!' + x.group(1) + '>')
  865. ]
  866. ROOT_TAG_NAME = u'[document]'
  867. HTML_ENTITIES = "html"
  868. XML_ENTITIES = "xml"
  869. XHTML_ENTITIES = "xhtml"
  870. # TODO: This only exists for backwards-compatibility
  871. ALL_ENTITIES = XHTML_ENTITIES
  872. # Used when determining whether a text node is all whitespace and
  873. # can be replaced with a single space. A text node that contains
  874. # fancy Unicode spaces (usually non-breaking) should be left
  875. # alone.
  876. STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, }
  877. def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None,
  878. markupMassage=True, smartQuotesTo=XML_ENTITIES,
  879. convertEntities=None, selfClosingTags=None, isHTML=False):
  880. """The Soup object is initialized as the 'root tag', and the
  881. provided markup (which can be a string or a file-like object)
  882. is fed into the underlying parser.
  883. sgmllib will process most bad HTML, and the BeautifulSoup
  884. class has some tricks for dealing with some HTML that kills
  885. sgmllib, but Beautiful Soup can nonetheless choke or lose data
  886. if your data uses self-closing tags or declarations
  887. incorrectly.
  888. By default, Beautiful Soup uses regexes to sanitize input,
  889. avoiding the vast majority of these problems. If the problems
  890. don't apply to you, pass in False for markupMassage, and
  891. you'll get better performance.
  892. The default parser massage techniques fix the two most common
  893. instances of invalid HTML that choke sgmllib:
  894. <br/> (No space between name of closing tag and tag close)
  895. <! --Comment--> (Extraneous whitespace in declaration)
  896. You can pass in a custom list of (RE object, replace method)
  897. tuples to get Beautiful Soup to scrub your input the way you
  898. want."""
  899. self.parseOnlyThese = parseOnlyThese
  900. self.fromEncoding = fromEncoding
  901. self.smartQuotesTo = smartQuotesTo
  902. self.convertEntities = convertEntities
  903. # Set the rules for how we'll deal with the entities we
  904. # encounter
  905. if self.convertEntities:
  906. # It doesn't make sense to convert encoded characters to
  907. # entities even while you're converting entities to Unicode.
  908. # Just convert it all to Unicode.
  909. self.smartQuotesTo = None
  910. if convertEntities == self.HTML_ENTITIES:
  911. self.convertXMLEntities = False
  912. self.convertHTMLEntities = True
  913. self.escapeUnrecognizedEntities = True
  914. elif convertEntities == self.XHTML_ENTITIES:
  915. self.convertXMLEntities = True
  916. self.convertHTMLEntities = True
  917. self.escapeUnrecognizedEntities = False
  918. elif convertEntities == self.XML_ENTITIES:
  919. self.convertXMLEntities = True
  920. self.convertHTMLEntities = False
  921. self.escapeUnrecognizedEntities = False
  922. else:
  923. self.convertXMLEntities = False
  924. self.convertHTMLEntities = False
  925. self.escapeUnrecognizedEntities = False
  926. self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
  927. SGMLParser.__init__(self)
  928. if hasattr(markup, 'read'): # It's a file-type object.
  929. markup = markup.read()
  930. self.markup = markup
  931. self.markupMassage = markupMassage
  932. try:
  933. self._feed(isHTML=isHTML)
  934. except StopParsing:
  935. pass
  936. self.markup = None # The markup can now be GCed
  937. def convert_charref(self, name):
  938. """This method fixes a bug in Python's SGMLParser."""
  939. try:
  940. n = int(name)
  941. except ValueError:
  942. return
  943. if not 0 <= n <= 127 : # ASCII ends at 127, not 255
  944. return
  945. return self.convert_codepoint(n)
  946. def _feed(self, inDocumentEncoding=None, isHTML=False):
  947. # Convert the document to Unicode.
  948. markup = self.markup
  949. if isinstance(markup, unicode):
  950. if not hasattr(self, 'originalEncoding'):
  951. self.originalEncoding = None
  952. else:
  953. dammit = UnicodeDammit\
  954. (markup, [self.fromEncoding, inDocumentEncoding],
  955. smartQuotesTo=self.smartQuotesTo, isHTML=isHTML)
  956. markup = dammit.unicode
  957. self.originalEncoding = dammit.originalEncoding
  958. self.declaredHTMLEncoding = dammit.declaredHTMLEncoding
  959. if markup:
  960. if self.markupMassage:
  961. if not isList(self.markupMassage):
  962. self.markupMassage = self.MARKUP_MASSAGE
  963. for fix, m in self.markupMassage:
  964. markup = fix.sub(m, markup)
  965. # TODO: We get rid of markupMassage so that the
  966. # soup object can be deepcopied later on. Some
  967. # Python installations can't copy regexes. If anyone
  968. # was relying on the existence of markupMassage, this
  969. # might cause problems.
  970. del(self.markupMassage)
  971. self.reset()
  972. SGMLParser.feed(self, markup)
  973. # Close out any unfinished strings and close all the open tags.
  974. self.endData()
  975. while self.currentTag.name != self.ROOT_TAG_NAME:
  976. self.popTag()
  977. def __getattr__(self, methodName):
  978. """This method routes method call requests to either the SGMLParser
  979. superclass or the Tag superclass, depending on the method name."""
  980. #print "__getattr__ called on %s.%s" % (self.__class__, methodName)
  981. if methodName.find('start_') == 0 or methodName.find('end_') == 0 \
  982. or methodName.find('do_') == 0:
  983. return SGMLParser.__getattr__(self, methodName)
  984. elif methodName.find('__') != 0:
  985. return Tag.__getattr__(self, methodName)
  986. else:
  987. raise AttributeError
  988. def isSelfClosingTag(self, name):
  989. """Returns true iff the given string is the name of a
  990. self-closing tag according to this parser."""
  991. return self.SELF_CLOSING_TAGS.has_key(name) \
  992. or self.instanceSelfClosingTags.has_key(name)
  993. def reset(self):
  994. Tag.__init__(self, self, self.ROOT_TAG_NAME)
  995. self.hidden = 1
  996. SGMLParser.reset(self)
  997. self.currentData = []
  998. self.currentTag = None
  999. self.tagStack = []
  1000. self.quoteStack = []
  1001. self.pushTag(self)
  1002. def popTag(self):
  1003. tag = self.tagStack.pop()
  1004. # Tags with just one string-owning child get the child as a
  1005. # 'string' property, so that soup.tag.string is shorthand for
  1006. # soup.tag.contents[0]
  1007. if len(self.currentTag.contents) == 1 and \
  1008. isinstance(self.currentTag.contents[0], NavigableString):
  1009. self.currentTag.string = self.currentTag.contents[0]
  1010. #print "Pop", tag.name
  1011. if self.tagStack:
  1012. self.currentTag = self.tagStack[-1]
  1013. return self.currentTag
  1014. def pushTag(self, tag):
  1015. #print "Push", tag.name
  1016. if self.currentTag:
  1017. self.currentTag.contents.append(tag)
  1018. self.tagStack.append(tag)
  1019. self.currentTag = self.tagStack[-1]
  1020. def endData(self, containerClass=NavigableString):
  1021. if self.currentData:
  1022. currentData = u''.join(self.currentData)
  1023. if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and
  1024. not set([tag.name for tag in self.tagStack]).intersection(
  1025. self.PRESERVE_WHITESPACE_TAGS)):
  1026. if '\n' in currentData:
  1027. currentData = '\n'
  1028. else:
  1029. currentData = ' '
  1030. self.currentData = []
  1031. if self.parseOnlyThese and len(self.tagStack) <= 1 and \
  1032. (not self.parseOnlyThese.text or \
  1033. not self.parseOnlyThese.search(currentData)):
  1034. return
  1035. o = containerClass(currentData)
  1036. o.setup(self.currentTag, self.previous)
  1037. if self.previous:
  1038. self.previous.next = o
  1039. self.previous = o
  1040. self.currentTag.contents.append(o)
  1041. def _popToTag(self, name, inclusivePop=True):
  1042. """Pops the tag stack up to and including the most recent
  1043. instance of the given tag. If inclusivePop is false, pops the tag
  1044. stack up to but *not* including the most recent instqance of
  1045. the given tag."""
  1046. #print "Popping to %s" % name
  1047. if name == self.ROOT_TAG_NAME:
  1048. return
  1049. numPops = 0
  1050. mostRecentTag = None
  1051. for i in range(len(self.tagStack)-1, 0, -1):
  1052. if name == self.tagStack[i].name:
  1053. numPops = len(self.tagStack)-i
  1054. break
  1055. if not inclusivePop:
  1056. numPops = numPops - 1
  1057. for i in range(0, numPops):
  1058. mostRecentTag = self.popTag()
  1059. return mostRecentTag
  1060. def _smartPop(self, name):
  1061. """We need to pop up to the previous tag of this type, unless
  1062. one of this tag's nesting reset triggers comes between this
  1063. tag and the previous tag of this type, OR unless this tag is a
  1064. generic nesting trigger and another generic nesting trigger
  1065. comes between this tag and the previous tag of this type.
  1066. Examples:
  1067. <p>Foo<b>Bar *<p>* should pop to 'p', not 'b'.
  1068. <p>Foo<table>Bar *<p>* should pop to 'table', not 'p'.
  1069. <p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'.
  1070. <li><ul><li> *<li>* should pop to 'ul', not the first 'li'.
  1071. <tr><table><tr> *<tr>* should pop to 'table', not the first 'tr'
  1072. <td><tr><td> *<td>* should pop to 'tr', not the first 'td'
  1073. """
  1074. nestingResetTriggers = self.NESTABLE_TAGS.get(name)
  1075. isNestable = nestingResetTriggers != None
  1076. isResetNesting = self.RESET_NESTING_TAGS.has_key(name)
  1077. popTo = None
  1078. inclusive = True
  1079. for i in range(len(self.tagStack)-1, 0, -1):
  1080. p = self.tagStack[i]
  1081. if (not p or p.name == name) and not isNestable:
  1082. #Non-nestable tags get popped to the top or to their
  1083. #last occurance.
  1084. popTo = name
  1085. break
  1086. if (nestingResetTriggers != None
  1087. and p.name in nestingResetTriggers) \
  1088. or (nestingResetTriggers == None and isResetNesting
  1089. and self.RESET_NESTING_TAGS.has_key(p.name)):
  1090. #If we encounter one of the nesting reset triggers
  1091. #peculiar to this tag, or we encounter another tag
  1092. #that causes nesting to reset, pop up to but not
  1093. #including that tag.
  1094. popTo = p.name
  1095. inclusive = False
  1096. break
  1097. p = p.parent
  1098. if popTo:
  1099. self._popToTag(popTo, inclusive)
  1100. def unknown_starttag(self, name, attrs, selfClosing=0):
  1101. #print "Start tag %s: %s" % (name, attrs)
  1102. if self.quoteStack:
  1103. #This is not a real tag.
  1104. #print "<%s> is not real!" % name
  1105. attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs))
  1106. self.handle_data('<%s%s>' % (name, attrs))
  1107. return
  1108. self.endData()
  1109. if not self.isSelfClosingTag(name) and not selfClosing:
  1110. self._smartPop(name)
  1111. if self.parseOnlyThese and len(self.tagStack) <= 1 \
  1112. and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)):
  1113. return
  1114. tag = Tag(self, name, attrs, self.currentTag, self.previous)
  1115. if self.previous:
  1116. self.previous.next = tag
  1117. self.previous = tag
  1118. self.pushTag(tag)
  1119. if selfClosing or self.isSelfClosingTag(name):
  1120. self.popTag()
  1121. if name in self.QUOTE_TAGS:
  1122. #print "Beginning quote (%s)" % name
  1123. self.quoteStack.append(name)
  1124. self.literal = 1
  1125. return tag
  1126. def unknown_endtag(self, name):
  1127. #print "End tag %s" % name
  1128. if self.quoteStack and self.quoteStack[-1] != name:
  1129. #This is not a real end tag.
  1130. #print "</%s> is not real!" % name
  1131. self.handle_data('</%s>' % name)
  1132. return
  1133. self.endData()
  1134. self._popToTag(name)
  1135. if self.quoteStack and self.quoteStack[-1] == name:
  1136. self.quoteStack.pop()
  1137. self.literal = (len(self.quoteStack) > 0)
  1138. def handle_data(self, data):
  1139. self.currentData.append(data)
  1140. def _toStringSubclass(self, text, subclass):
  1141. """Adds a certain piece of text to the tree as a NavigableString
  1142. subclass."""
  1143. self.endData()
  1144. self.handle_data(text)
  1145. self.endData(subclass)
  1146. def handle_pi(self, text):
  1147. """Handle a processing instruction as a ProcessingInstruction
  1148. object, possibly one with a %SOUP-ENCODING% slot into which an
  1149. encoding will be plugged later."""
  1150. if text[:3] == "xml":
  1151. text = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
  1152. self._toStringSubclass(text, ProcessingInstruction)
  1153. def handle_comment(self, text):
  1154. "Handle comments as Comment objects."
  1155. self._toStringSubclass(text, Comment)
  1156. def handle_charref(self, ref):
  1157. "Handle character references as data."
  1158. if self.convertEntities:
  1159. data = unichr(int(ref))
  1160. else:
  1161. data = '&#%s;' % ref
  1162. self.handle_data(data)
  1163. def handle_entityref(self, ref):
  1164. """Handle entity references as data, possibly converting known
  1165. HTML and/or XML entity references to the corresponding Unicode
  1166. characters."""
  1167. data = None
  1168. if self.convertHTMLEntities:
  1169. try:
  1170. data = unichr(name2codepoint[ref])
  1171. except KeyError:
  1172. pass
  1173. if not data and self.convertXMLEntities:
  1174. data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref)
  1175. if not data and self.convertHTMLEntities and \
  1176. not self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref):
  1177. # TODO: We've got a problem here. We're told this is
  1178. # an entity reference, but it's not an XML entity
  1179. # reference or an HTML entity reference. Nonetheless,
  1180. # the logical thing to do is to pass it through as an
  1181. # unrecognized entity reference.
  1182. #
  1183. # Except: when the input is "&carol;" this function
  1184. # will be called with input "carol". When the input is
  1185. # "AT&T", this function will be called with input
  1186. # "T". We have no way of knowing whether a semicolon
  1187. # was present originally, so we don't know whether
  1188. # this is an unknown entity or just a misplaced
  1189. # ampersand.
  1190. #
  1191. # The more common case is a misplaced ampersand, so I
  1192. # escape the ampersand and omit the trailing semicolon.
  1193. data = "&amp;%s" % ref
  1194. if not data:
  1195. # This case is different from the one above, because we
  1196. # haven't already gone through a supposedly comprehensive
  1197. # mapping of entities to Unicode characters. We might not
  1198. # have gone through any mapping at all. So the chances are
  1199. # very high that this is a real entity, and not a
  1200. # misplaced ampersand.
  1201. data = "&%s;" % ref
  1202. self.handle_data(data)
  1203. def handle_decl(self, data):
  1204. "Handle DOCTYPEs and the like as Declaration objects."
  1205. self._toStringSubclass(data, Declaration)
  1206. def parse_declaration(self, i):
  1207. """Treat a bogus SGML declaration as raw data. Treat a CDATA
  1208. declaration as a CData object."""
  1209. j = None
  1210. if self.rawdata[i:i+9] == '<![CDATA[':
  1211. k = self.rawdata.find(']]>', i)
  1212. if k == -1:
  1213. k = len(self.rawdata)
  1214. data = self.rawdata[i+9:k]
  1215. j = k+3
  1216. self._toStringSubclass(data, CData)
  1217. else:
  1218. try:
  1219. j = SGMLParser.parse_declaration(self, i)
  1220. except SGMLParseError:
  1221. toHandle = self.rawdata[i:]
  1222. self.handle_data(toHandle)
  1223. j = i + len(toHandle)
  1224. return j
  1225. class BeautifulSoup(BeautifulStoneSoup):
  1226. """This parser knows the following facts about HTML:
  1227. * Some tags have no closing tag and should be interpreted as being
  1228. closed as soon as they are encountered.
  1229. * The text inside some tags (ie. 'script') may contain tags which
  1230. are not really part of the document and which should be parsed
  1231. as text, not tags. If you want to parse the text as tags, you can
  1232. always fetch it and parse it explicitly.
  1233. * Tag nesting rules:
  1234. Most tags can't be nested at all. For instance, the occurance of
  1235. a <p> tag should implicitly close the previous <p> tag.
  1236. <p>Para1<p>Para2
  1237. should be transformed into:
  1238. <p>Para1</p><p>Para2
  1239. Some tags can be nested arbitrarily. For instance, the occurance
  1240. of a <blockquote> tag should _not_ implicitly close the previous
  1241. <blockquote> tag.
  1242. Alice said: <blockquote>Bob said: <blockquote>Blah
  1243. should NOT be transformed into:
  1244. Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah
  1245. Some tags can be nested, but the nesting is reset by the
  1246. interposition of other tags. For instance, a <tr> tag should
  1247. implicitly close the previous <tr> tag within the same <table>,
  1248. but not close a <tr> tag in another table.
  1249. <table><tr>Blah<tr>Blah
  1250. should be transformed into:
  1251. <table><tr>Blah</tr><tr>Blah
  1252. but,
  1253. <tr>Blah<table><tr>Blah
  1254. should NOT be transformed into
  1255. <tr>Blah<table></tr><tr>Blah
  1256. Differing assumptions about tag nesting rules are a major source
  1257. of problems with the BeautifulSoup class. If BeautifulSoup is not
  1258. treating as nestable a tag your page author treats as nestable,
  1259. try ICantBelieveItsBeautifulSoup, MinimalSoup, or
  1260. BeautifulStoneSoup before writing your own subclass."""
  1261. def __init__(self, *args, **kwargs):
  1262. if not kwargs.has_key('smartQuotesTo'):
  1263. kwargs['smartQuotesTo'] = self.HTML_ENTITIES
  1264. kwargs['isHTML'] = True
  1265. BeautifulStoneSoup.__init__(self, *args, **kwargs)
  1266. SELF_CLOSING_TAGS = buildTagMap(None,
  1267. ['br' , 'hr', 'input', 'img', 'meta',
  1268. 'spacer', 'link', 'frame', 'base'])
  1269. PRESERVE_WHITESPACE_TAGS = set(['pre', 'textarea'])
  1270. QUOTE_TAGS = {'script' : None, 'textarea' : None}
  1271. #According to the HTML standard, each of these inline tags can
  1272. #contain another tag of the same type. Furthermore, it's common
  1273. #to actually use these tags this way.
  1274. NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup',
  1275. 'center']
  1276. #According to the HTML standard, these block tags can contain
  1277. #another tag of the same type. Furthermore, it's common
  1278. #to actually use these tags this way.
  1279. NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
  1280. #Lists can contain other lists, but there are restrictions.
  1281. NESTABLE_LIST_TAGS = { 'ol' : [],
  1282. 'ul' : [],
  1283. 'li' : ['ul', 'ol'],
  1284. 'dl' : [],
  1285. 'dd' : ['dl'],
  1286. 'dt' : ['dl'] }
  1287. #Tables can contain other tables, but there are restrictions.
  1288. NESTABLE_TABLE_TAGS = {'table' : [],
  1289. 'tr' : ['table', 'tbody', 'tfoot', 'thead'],
  1290. 'td' : ['tr'],
  1291. 'th' : ['tr'],
  1292. 'thead' : ['table'],
  1293. 'tbody' : ['table'],
  1294. 'tfoot' : ['table'],
  1295. }
  1296. NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre']
  1297. #If one of these tags is encountered, all tags up to the next tag of
  1298. #this type are popped.
  1299. RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript',
  1300. NON_NESTABLE_BLOCK_TAGS,
  1301. NESTABLE_LIST_TAGS,
  1302. NESTABLE_TABLE_TAGS)
  1303. NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS,
  1304. NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS)
  1305. # Used to detect the charset in a META tag; see start_meta
  1306. CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M)
  1307. def start_meta(self, attrs):
  1308. """Beautiful Soup can detect a charset included in a META tag,
  1309. try to convert the document to that charset, and re-parse the
  1310. document from the beginning."""
  1311. httpEquiv = None
  1312. contentType = None
  1313. contentTypeIndex = None
  1314. tagNeedsEncodingSubstitution = False
  1315. for i in range(0, len(attrs)):
  1316. key, value = attrs[i]
  1317. key = key.lower()
  1318. if key == 'http-equiv':
  1319. httpEquiv = value
  1320. elif key == 'content':
  1321. contentType = value
  1322. contentTypeIndex = i
  1323. if httpEquiv and contentType: # It's an interesting meta tag.
  1324. match = self.CHARSET_RE.search(contentType)
  1325. if match:
  1326. if (self.declaredHTMLEncoding is not None or
  1327. self.originalEncoding == self.fromEncoding):
  1328. # An HTML encoding was sniffed while converting
  1329. # the document to Unicode, or an HTML encoding was
  1330. # sniffed during a previous pass through the
  1331. # document, or an encoding was specified
  1332. # explicitly and it worked. Rewrite the meta tag.
  1333. def rewrite(match):
  1334. return match.group(1) + "%SOUP-ENCODING%"
  1335. newAttr = self.CHARSET_RE.sub(rewrite, contentType)
  1336. attrs[contentTypeIndex] = (attrs[contentTypeIndex][0],
  1337. newAttr)
  1338. tagNeedsEncodingSubstitution = True
  1339. else:
  1340. # This is our first pass through the document.
  1341. # Go through it again with the encoding information.
  1342. newCharset = match.group(3)
  1343. if newCharset and newCharset != self.originalEncoding:
  1344. self.declaredHTMLEncoding = newCharset
  1345. self._feed(self.declaredHTMLEncoding)
  1346. raise StopParsing
  1347. pass
  1348. tag = self.unknown_starttag("meta", attrs)
  1349. if tag and tagNeedsEncodingSubstitution:
  1350. tag.containsSubstitutions = True
  1351. class StopParsing(Exception):
  1352. pass
  1353. class ICantBelieveItsBeautifulSoup(BeautifulSoup):
  1354. """The BeautifulSoup class is oriented towards skipping over
  1355. common HTML errors like unclosed tags. However, sometimes it makes
  1356. errors of its own. For instance, consider this fragment:
  1357. <b>Foo<b>Bar</b></b>
  1358. This is perfectly valid (if bizarre) HTML. However, the
  1359. BeautifulSoup class will implicitly close the first b tag when it
  1360. encounters the second 'b'. It will think the author wrote
  1361. "<b>Foo<b>Bar", and didn't close the first 'b' tag, because
  1362. there's no real-world reason to bold something that's already
  1363. bold. When it encounters '</b></b>' it will close two more 'b'
  1364. tags, for a grand total of three tags closed instead of two. This
  1365. can throw off the rest of your document structure. The same is
  1366. true of a number of other tags, listed below.
  1367. It's much more common for someone to forget to close a 'b' tag
  1368. than to actually use nested 'b' tags, and the BeautifulSoup class
  1369. handles the common case. This class handles the not-co-common
  1370. case: where you can't believe someone wrote what they did, but
  1371. it's valid HTML and BeautifulSoup screwed up by assuming it
  1372. wouldn't be."""
  1373. I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \
  1374. ['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong',
  1375. 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b',
  1376. 'big']
  1377. I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript']
  1378. NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS,
  1379. I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS,
  1380. I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS)
  1381. class MinimalSoup(BeautifulSoup):
  1382. """The MinimalSoup class is for parsing HTML that contains
  1383. pathologically bad markup. It makes no assumptions about tag
  1384. nesting, but it does know which tags are self-closing, that
  1385. <script> tags contain Javascript and should not be parsed, that
  1386. META tags may contain encoding information, and so on.
  1387. This also makes it better for subclassing than BeautifulStoneSoup
  1388. or BeautifulSoup."""
  1389. RESET_NESTING_TAGS = buildTagMap('noscript')
  1390. NESTABLE_TAGS = {}
  1391. class BeautifulSOAP(BeautifulStoneSoup):
  1392. """This class will push a tag with only a single string child into
  1393. the tag's parent as an attribute. The attribute's name is the tag
  1394. name, and the value is the string child. An example should give
  1395. the flavor of the change:
  1396. <foo><bar>baz</bar></foo>
  1397. =>
  1398. <foo bar="baz"><bar>baz</bar></foo>
  1399. You can then access fooTag['bar'] instead of fooTag.barTag.string.
  1400. This is, of course, useful for scraping structures that tend to
  1401. use subelements instead of attributes, such as SOAP messages. Note
  1402. that it modifies its input, so don't print the modified version
  1403. out.
  1404. I'm not sure how many people really want to use this class; let me
  1405. know if you do. Mainly I like the name."""
  1406. def popTag(self):
  1407. if len(self.tagStack) > 1:
  1408. tag = self.tagStack[-1]
  1409. parent = self.tagStack[-2]
  1410. parent._getAttrMap()
  1411. if (isinstance(tag, Tag) and len(tag.contents) == 1 and
  1412. isinstance(tag.contents[0], NavigableString) and
  1413. not parent.attrMap.has_key(tag.name)):
  1414. parent[tag.name] = tag.contents[0]
  1415. BeautifulStoneSoup.popTag(self)
  1416. #Enterprise class names! It has come to our attention that some people
  1417. #think the names of the Beautiful Soup parser classes are too silly
  1418. #and "unprofessional" for use in enterprise screen-scraping. We feel
  1419. #your pain! For such-minded folk, the Beautiful Soup Consortium And
  1420. #All-Night Kosher Bakery recommends renaming this file to
  1421. #"RobustParser.py" (or, in cases of extreme enterprisiness,
  1422. #"RobustParserBeanInterface.class") and using the following
  1423. #enterprise-friendly class aliases:
  1424. class RobustXMLParser(BeautifulStoneSoup):
  1425. pass
  1426. class RobustHTMLParser(BeautifulSoup):
  1427. pass
  1428. class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup):
  1429. pass
  1430. class RobustInsanelyWackAssHTMLParser(MinimalSoup):
  1431. pass
  1432. class SimplifyingSOAPParser(BeautifulSOAP):
  1433. pass
  1434. ######################################################
  1435. #
  1436. # Bonus library: Unicode, Dammit
  1437. #
  1438. # This class forces XML data into a standard format (usually to UTF-8
  1439. # or Unicode). It is heavily based on code from Mark Pilgrim's
  1440. # Universal Feed Parser. It does not rewrite the XML or HTML to
  1441. # reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi
  1442. # (XML) and BeautifulSoup.start_meta (HTML).
  1443. # Autodetects character encodings.
  1444. # Download from http://chardet.feedparser.org/
  1445. try:
  1446. import chardet
  1447. # import chardet.constants
  1448. # chardet.constants._debug = 1
  1449. except ImportError:
  1450. chardet = None
  1451. # cjkcodecs and iconv_codec make Python know about more character encodings.
  1452. # Both are available from http://cjkpython.i18n.org/
  1453. # They're built in if you use Python 2.4.
  1454. try:
  1455. import cjkcodecs.aliases
  1456. except ImportError:
  1457. pass
  1458. try:
  1459. import iconv_codec
  1460. except ImportError:
  1461. pass
  1462. class UnicodeDammit:
  1463. """A class for detecting the encoding of a *ML document and
  1464. converting it to a Unicode string. If the source encoding is
  1465. windows-1252, can replace MS smart quotes with their HTML or XML
  1466. equivalents."""
  1467. # This dictionary maps commonly seen values for "charset" in HTML
  1468. # meta tags to the corresponding Python codec names. It only covers
  1469. # values that aren't in Python's aliases and can't be determined
  1470. # by the heuristics in find_codec.
  1471. CHARSET_ALIASES = { "macintosh" : "mac-roman",
  1472. "x-sjis" : "shift-jis" }
  1473. def __init__(self, markup, overrideEncodings=[],
  1474. smartQuotesTo='xml', isHTML=False):
  1475. self.declaredHTMLEncoding = None
  1476. self.markup, documentEncoding, sniffedEncoding = \
  1477. self._detectEncoding(markup, isHTML)
  1478. self.smartQuotesTo = smartQuotesTo
  1479. self.triedEncodings = []
  1480. if markup == '' or isinstance(markup, unicode):
  1481. self.originalEncoding = None
  1482. self.unicode = unicode(markup)
  1483. return
  1484. u = None
  1485. for proposedEncoding in overrideEncodings:
  1486. u = self._convertFrom(proposedEncoding)
  1487. if u: break
  1488. if not u:
  1489. for proposedEncoding in (documentEncoding, sniffedEncoding):
  1490. u = self._convertFrom(proposedEncoding)
  1491. if u: break
  1492. # If no luck and we have auto-detection library, try that:
  1493. if not u and chardet and not isinstance(self.markup, unicode):
  1494. u = self._convertFrom(chardet.detect(self.markup)['encoding'])
  1495. # As a last resort, try utf-8 and windows-1252:
  1496. if not u:
  1497. for proposed_encoding in ("utf-8", "windows-1252"):
  1498. u = self._convertFrom(proposed_encoding)
  1499. if u: break
  1500. self.unicode = u
  1501. if not u: self.originalEncoding = None
  1502. def _subMSChar(self, orig):
  1503. """Changes a MS smart quote character to an XML or HTML
  1504. entity."""
  1505. sub = self.MS_CHARS.get(orig)
  1506. if type(sub) == types.TupleType:
  1507. if self.smartQuotesTo == 'xml':
  1508. sub = '&#x%s;' % sub[1]
  1509. else:
  1510. sub = '&%s;' % sub[0]
  1511. return sub
  1512. def _convertFrom(self, proposed):
  1513. proposed = self.find_codec(proposed)
  1514. if not proposed or proposed in self.triedEncodings:
  1515. return None
  1516. self.triedEncodings.append(proposed)
  1517. markup = self.markup
  1518. # Convert smart quotes to HTML if coming from an encoding
  1519. # that might have them.
  1520. if self.smartQuotesTo and proposed.lower() in("windows-1252",
  1521. "iso-8859-1",
  1522. "iso-8859-2"):
  1523. markup = re.compile("([\x80-\x9f])").sub \
  1524. (lambda(x): self._subMSChar(x.group(1)),
  1525. markup)
  1526. try:
  1527. # print "Trying to convert document to %s" % proposed
  1528. u = self._toUnicode(markup, proposed)
  1529. self.markup = u
  1530. self.originalEncoding = proposed
  1531. except Exception, e:
  1532. # print "That didn't work!"
  1533. # print e
  1534. return None
  1535. #print "Correct encoding: %s" % proposed
  1536. return self.markup
  1537. def _toUnicode(self, data, encoding):
  1538. '''Given a string and its encoding, decodes the string into Unicode.
  1539. %encoding is a string recognized by encodings.aliases'''
  1540. # strip Byte Order Mark (if present)
  1541. if (len(data) >= 4) and (data[:2] == '\xfe\xff') \
  1542. and (data[2:4] != '\x00\x00'):
  1543. encoding = 'utf-16be'
  1544. data = data[2:]
  1545. elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \
  1546. and (data[2:4] != '\x00\x00'):
  1547. encoding = 'utf-16le'
  1548. data = data[2:]
  1549. elif data[:3] == '\xef\xbb\xbf':
  1550. encoding = 'utf-8'
  1551. data = data[3:]
  1552. elif data[:4] == '\x00\x00\xfe\xff':
  1553. encoding = 'utf-32be'
  1554. data = data[4:]
  1555. elif data[:4] == '\xff\xfe\x00\x00':
  1556. encoding = 'utf-32le'
  1557. data = data[4:]
  1558. newdata = unicode(data, encoding)
  1559. return newdata
  1560. def _detectEncoding(self, xml_data, isHTML=False):
  1561. """Given a document, tries to detect its XML encoding."""
  1562. xml_encoding = sniffed_xml_encoding = None
  1563. try:
  1564. if xml_data[:4] == '\x4c\x6f\xa7\x94':
  1565. # EBCDIC
  1566. xml_data = self._ebcdic_to_ascii(xml_data)
  1567. elif xml_data[:4] == '\x00\x3c\x00\x3f':
  1568. # UTF-16BE
  1569. sniffed_xml_encoding = 'utf-16be'
  1570. xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
  1571. elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \
  1572. and (xml_data[2:4] != '\x00\x00'):
  1573. # UTF-16BE with BOM
  1574. sniffed_xml_encoding = 'utf-16be'
  1575. xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
  1576. elif xml_data[:4] == '\x3c\x00\x3f\x00':
  1577. # UTF-16LE
  1578. sniffed_xml_encoding = 'utf-16le'
  1579. xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
  1580. elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \
  1581. (xml_data[2:4] != '\x00\x00'):
  1582. # UTF-16LE with BOM
  1583. sniffed_xml_encoding = 'utf-16le'
  1584. xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
  1585. elif xml_data[:4] == '\x00\x00\x00\x3c':
  1586. # UTF-32BE
  1587. sniffed_xml_encoding = 'utf-32be'
  1588. xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
  1589. elif xml_data[:4] == '\x3c\x00\x00\x00':
  1590. # UTF-32LE
  1591. sniffed_xml_encoding = 'utf-32le'
  1592. xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
  1593. elif xml_data[:4] == '\x00\x00\xfe\xff':
  1594. # UTF-32BE with BOM
  1595. sniffed_xml_encoding = 'utf-32be'
  1596. xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
  1597. elif xml_data[:4] == '\xff\xfe\x00\x00':
  1598. # UTF-32LE with BOM
  1599. sniffed_xml_encoding = 'utf-32le'
  1600. xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
  1601. elif xml_data[:3] == '\xef\xbb\xbf':
  1602. # UTF-8 with BOM
  1603. sniffed_xml_encoding = 'utf-8'
  1604. xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
  1605. else:
  1606. sniffed_xml_encoding = 'ascii'
  1607. pass
  1608. except:
  1609. xml_encoding_match = None
  1610. xml_encoding_match = re.compile(
  1611. '^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
  1612. if not xml_encoding_match and isHTML:
  1613. regexp = re.compile('<\s*meta[^>]+charset=([^>]*?)[;\'">]', re.I)
  1614. xml_encoding_match = regexp.search(xml_data)
  1615. if xml_encoding_match is not None:
  1616. xml_encoding = xml_encoding_match.groups()[0].lower()
  1617. if isHTML:
  1618. self.declaredHTMLEncoding = xml_encoding
  1619. if sniffed_xml_encoding and \
  1620. (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',
  1621. 'iso-10646-ucs-4', 'ucs-4', 'csucs4',
  1622. 'utf-16', 'utf-32', 'utf_16', 'utf_32',
  1623. 'utf16', 'u16')):
  1624. xml_encoding = sniffed_xml_encoding
  1625. return xml_data, xml_encoding, sniffed_xml_encoding
  1626. def find_codec(self, charset):
  1627. return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \
  1628. or (charset and self._codec(charset.replace("-", ""))) \
  1629. or (charset and self._codec(charset.replace("-", "_"))) \
  1630. or charset
  1631. def _codec(self, charset):
  1632. if not charset: return charset
  1633. codec = None
  1634. try:
  1635. codecs.lookup(charset)
  1636. codec = charset
  1637. except (LookupError, ValueError):
  1638. pass
  1639. return codec
  1640. EBCDIC_TO_ASCII_MAP = None
  1641. def _ebcdic_to_ascii(self, s):
  1642. c = self.__class__
  1643. if not c.EBCDIC_TO_ASCII_MAP:
  1644. emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
  1645. 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
  1646. 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
  1647. 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
  1648. 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
  1649. 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
  1650. 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
  1651. 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
  1652. 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,
  1653. 201,202,106,107,108,109,110,111,112,113,114,203,204,205,
  1654. 206,207,208,209,126,115,116,117,118,119,120,121,122,210,
  1655. 211,212,213,214,215,216,217,218,219,220,221,222,223,224,
  1656. 225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72,
  1657. 73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81,
  1658. 82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89,
  1659. 90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57,
  1660. 250,251,252,253,254,255)
  1661. import string
  1662. c.EBCDIC_TO_ASCII_MAP = string.maketrans( \
  1663. ''.join(map(chr, range(256))), ''.join(map(chr, emap)))
  1664. return s.translate(c.EBCDIC_TO_ASCII_MAP)
  1665. MS_CHARS = { '\x80' : ('euro', '20AC'),
  1666. '\x81' : ' ',
  1667. '\x82' : ('sbquo', '201A'),
  1668. '\x83' : ('fnof', '192'),
  1669. '\x84' : ('bdquo', '201E'),
  1670. '\x85' : ('hellip', '2026'),
  1671. '\x86' : ('dagger', '2020'),
  1672. '\x87' : ('Dagger', '2021'),
  1673. '\x88' : ('circ', '2C6'),
  1674. '\x89' : ('permil', '2030'),
  1675. '\x8A' : ('Scaron', '160'),
  1676. '\x8B' : ('lsaquo', '2039'),
  1677. '\x8C' : ('OElig', '152'),
  1678. '\x8D' : '?',
  1679. '\x8E' : ('#x17D', '17D'),
  1680. '\x8F' : '?',
  1681. '\x90' : '?',
  1682. '\x91' : ('lsquo', '2018'),
  1683. '\x92' : ('rsquo', '2019'),
  1684. '\x93' : ('ldquo', '201C'),
  1685. '\x94' : ('rdquo', '201D'),
  1686. '\x95' : ('bull', '2022'),
  1687. '\x96' : ('ndash', '2013'),
  1688. '\x97' : ('mdash', '2014'),
  1689. '\x98' : ('tilde', '2DC'),
  1690. '\x99' : ('trade', '2122'),
  1691. '\x9a' : ('scaron', '161'),
  1692. '\x9b' : ('rsaquo', '203A'),
  1693. '\x9c' : ('oelig', '153'),
  1694. '\x9d' : '?',
  1695. '\x9e' : ('#x17E', '17E'),
  1696. '\x9f' : ('Yuml', ''),}
  1697. #######################################################################
  1698. #By default, act as an HTML pretty-printer.
  1699. if __name__ == '__main__':
  1700. import sys
  1701. soup = BeautifulSoup(sys.stdin)
  1702. print soup.prettify()