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

/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py

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