BeautifulSoup.py 78 KB

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