Incomplete webapp to aggregate achievements/badges from various sources
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BeautifulSoup.py 78KB

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