PageRenderTime 41ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/punkscan/punk_solr/pysolr/BeautifulSoup.py

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