PageRenderTime 1187ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/scripts/python/xgoogle/BeautifulSoup.py

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