PageRenderTime 71ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/other/FetchData/BeautifulSoup.py

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