PageRenderTime 53ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/crunchy/src/element_tree3/BeautifulSoup.py

http://crunchy.googlecode.com/
Python | 2015 lines | 1804 code | 82 blank | 129 comment | 132 complexity | 064a4075940c726f85379a88ccc22a86 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. """Beautiful Soup
  2. Elixir and Tonic
  3. "The Screen-Scraper's Friend"
  4. http://www.crummy.com/software/BeautifulSoup/
  5. Beautiful Soup parses a (possibly invalid) XML or HTML document into a
  6. tree representation. It provides methods and Pythonic idioms that make
  7. it easy to navigate, search, and modify the tree.
  8. A well-formed XML/HTML document yields a well-formed data
  9. structure. An ill-formed XML/HTML document yields a correspondingly
  10. ill-formed data structure. If your document is only locally
  11. well-formed, you can use this library to find and process the
  12. well-formed part of it.
  13. Beautiful Soup works with Python 2.2 and up. It has no external
  14. dependencies, but you'll have more success at converting data to UTF-8
  15. if you also install these three packages:
  16. * chardet, for auto-detecting character encodings
  17. http://chardet.feedparser.org/
  18. * cjkcodecs and iconv_codec, which add more encodings to the ones supported
  19. by stock Python.
  20. http://cjkpython.i18n.org/
  21. Beautiful Soup defines classes for two main parsing strategies:
  22. * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific
  23. language that kind of looks like XML.
  24. * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid
  25. or invalid. This class has web browser-like heuristics for
  26. obtaining a sensible parse tree in the face of common HTML errors.
  27. Beautiful Soup also defines a class (UnicodeDammit) for autodetecting
  28. the encoding of an HTML or XML document, and converting it to
  29. Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser.
  30. For more than you ever wanted to know about Beautiful Soup, see the
  31. documentation:
  32. http://www.crummy.com/software/BeautifulSoup/documentation.html
  33. Here, have some legalese:
  34. Copyright (c) 2004-2009, Leonard Richardson
  35. All rights reserved.
  36. Redistribution and use in source and binary forms, with or without
  37. modification, are permitted provided that the following conditions are
  38. met:
  39. * Redistributions of source code must retain the above copyright
  40. notice, this list of conditions and the following disclaimer.
  41. * Redistributions in binary form must reproduce the above
  42. copyright notice, this list of conditions and the following
  43. disclaimer in the documentation and/or other materials provided
  44. with the distribution.
  45. * Neither the name of the the Beautiful Soup Consortium and All
  46. Night Kosher Bakery nor the names of its contributors may be
  47. used to endorse or promote products derived from this software
  48. without specific prior written permission.
  49. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  50. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  51. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  52. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  53. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  54. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  55. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  56. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  57. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  58. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  59. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT.
  60. """
  61. __author__ = "Leonard Richardson (leonardr@segfault.org)"
  62. __version__ = "3.1.0.1"
  63. __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson"
  64. __license__ = "New-style BSD"
  65. import codecs
  66. import _markupbase
  67. import sys
  68. import types
  69. import re
  70. from html.parser import HTMLParser, HTMLParseError
  71. try:
  72. from html.entities import name2codepoint
  73. except ImportError:
  74. name2codepoint = {}
  75. try:
  76. set
  77. except NameError:
  78. from sets import Set as set
  79. #These hacks make Beautiful Soup able to parse XML with namespaces
  80. _markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match
  81. DEFAULT_OUTPUT_ENCODING = "utf-8"
  82. # First, the classes that represent markup elements.
  83. def sob(str, encoding):
  84. """Returns either the given Unicode string or its encoding."""
  85. if encoding is None:
  86. return str
  87. else:
  88. return str.encode(encoding)
  89. class PageElement:
  90. """Contains the navigational information for some part of the page
  91. (either a tag or a piece of text)"""
  92. def setup(self, parent=None, previous=None):
  93. """Sets up the initial relations between this element and
  94. other elements."""
  95. self.parent = parent
  96. self.previous = previous
  97. self.next = None
  98. self.previousSibling = None
  99. self.nextSibling = None
  100. if self.parent and self.parent.contents:
  101. self.previousSibling = self.parent.contents[-1]
  102. self.previousSibling.nextSibling = self
  103. def replaceWith(self, replaceWith):
  104. oldParent = self.parent
  105. myIndex = self.parent.contents.index(self)
  106. if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent:
  107. # We're replacing this element with one of its siblings.
  108. index = self.parent.contents.index(replaceWith)
  109. if index and index < myIndex:
  110. # Furthermore, it comes before this element. That
  111. # means that when we extract it, the index of this
  112. # element will change.
  113. myIndex = myIndex - 1
  114. self.extract()
  115. oldParent.insert(myIndex, replaceWith)
  116. def extract(self):
  117. """Destructively rips this element out of the tree."""
  118. if self.parent:
  119. try:
  120. self.parent.contents.remove(self)
  121. except ValueError:
  122. pass
  123. #Find the two elements that would be next to each other if
  124. #this element (and any children) hadn't been parsed. Connect
  125. #the two.
  126. lastChild = self._lastRecursiveChild()
  127. nextElement = lastChild.__next__
  128. if self.previous:
  129. self.previous.next = nextElement
  130. if nextElement:
  131. nextElement.previous = self.previous
  132. self.previous = None
  133. lastChild.next = None
  134. self.parent = None
  135. if self.previousSibling:
  136. self.previousSibling.nextSibling = self.nextSibling
  137. if self.nextSibling:
  138. self.nextSibling.previousSibling = self.previousSibling
  139. self.previousSibling = self.nextSibling = None
  140. return self
  141. def _lastRecursiveChild(self):
  142. "Finds the last element beneath this object to be parsed."
  143. lastChild = self
  144. while hasattr(lastChild, 'contents') and lastChild.contents:
  145. lastChild = lastChild.contents[-1]
  146. return lastChild
  147. def insert(self, position, newChild):
  148. if (isinstance(newChild, str)
  149. or isinstance(newChild, str)) \
  150. and not isinstance(newChild, NavigableString):
  151. newChild = NavigableString(newChild)
  152. position = min(position, len(self.contents))
  153. if hasattr(newChild, 'parent') and newChild.parent != None:
  154. # We're 'inserting' an element that's already one
  155. # of this object's children.
  156. if newChild.parent == self:
  157. index = self.find(newChild)
  158. if index and index < position:
  159. # Furthermore we're moving it further down the
  160. # list of this object's children. That means that
  161. # when we extract this element, our target index
  162. # will jump down one.
  163. position = position - 1
  164. newChild.extract()
  165. newChild.parent = self
  166. previousChild = None
  167. if position == 0:
  168. newChild.previousSibling = None
  169. newChild.previous = self
  170. else:
  171. previousChild = self.contents[position-1]
  172. newChild.previousSibling = previousChild
  173. newChild.previousSibling.nextSibling = newChild
  174. newChild.previous = previousChild._lastRecursiveChild()
  175. if newChild.previous:
  176. newChild.previous.next = newChild
  177. newChildsLastElement = newChild._lastRecursiveChild()
  178. if position >= len(self.contents):
  179. newChild.nextSibling = None
  180. parent = self
  181. parentsNextSibling = None
  182. while not parentsNextSibling:
  183. parentsNextSibling = parent.nextSibling
  184. parent = parent.parent
  185. if not parent: # This is the last element in the document.
  186. break
  187. if parentsNextSibling:
  188. newChildsLastElement.next = parentsNextSibling
  189. else:
  190. newChildsLastElement.next = None
  191. else:
  192. nextChild = self.contents[position]
  193. newChild.nextSibling = nextChild
  194. if newChild.nextSibling:
  195. newChild.nextSibling.previousSibling = newChild
  196. newChildsLastElement.next = nextChild
  197. if newChildsLastElement.__next__:
  198. newChildsLastElement.next.previous = newChildsLastElement
  199. self.contents.insert(position, newChild)
  200. def append(self, tag):
  201. """Appends the given tag to the contents of this tag."""
  202. self.insert(len(self.contents), tag)
  203. def findNext(self, name=None, attrs={}, text=None, **kwargs):
  204. """Returns the first item that matches the given criteria and
  205. appears after this Tag in the document."""
  206. return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
  207. def findAllNext(self, name=None, attrs={}, text=None, limit=None,
  208. **kwargs):
  209. """Returns all items that match the given criteria and appear
  210. after this Tag in the document."""
  211. return self._findAll(name, attrs, text, limit, self.nextGenerator,
  212. **kwargs)
  213. def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
  214. """Returns the closest sibling to this Tag that matches the
  215. given criteria and appears after this Tag in the document."""
  216. return self._findOne(self.findNextSiblings, name, attrs, text,
  217. **kwargs)
  218. def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,
  219. **kwargs):
  220. """Returns the siblings of this Tag that match the given
  221. criteria and appear after this Tag in the document."""
  222. return self._findAll(name, attrs, text, limit,
  223. self.nextSiblingGenerator, **kwargs)
  224. fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x
  225. def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
  226. """Returns the first item that matches the given criteria and
  227. appears before this Tag in the document."""
  228. return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
  229. def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,
  230. **kwargs):
  231. """Returns all items that match the given criteria and appear
  232. before this Tag in the document."""
  233. return self._findAll(name, attrs, text, limit, self.previousGenerator,
  234. **kwargs)
  235. fetchPrevious = findAllPrevious # Compatibility with pre-3.x
  236. def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
  237. """Returns the closest sibling to this Tag that matches the
  238. given criteria and appears before this Tag in the document."""
  239. return self._findOne(self.findPreviousSiblings, name, attrs, text,
  240. **kwargs)
  241. def findPreviousSiblings(self, name=None, attrs={}, text=None,
  242. limit=None, **kwargs):
  243. """Returns the siblings of this Tag that match the given
  244. criteria and appear before this Tag in the document."""
  245. return self._findAll(name, attrs, text, limit,
  246. self.previousSiblingGenerator, **kwargs)
  247. fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x
  248. def findParent(self, name=None, attrs={}, **kwargs):
  249. """Returns the closest parent of this Tag that matches the given
  250. criteria."""
  251. # NOTE: We can't use _findOne because findParents takes a different
  252. # set of arguments.
  253. r = None
  254. l = self.findParents(name, attrs, 1)
  255. if l:
  256. r = l[0]
  257. return r
  258. def findParents(self, name=None, attrs={}, limit=None, **kwargs):
  259. """Returns the parents of this Tag that match the given
  260. criteria."""
  261. return self._findAll(name, attrs, None, limit, self.parentGenerator,
  262. **kwargs)
  263. fetchParents = findParents # Compatibility with pre-3.x
  264. #These methods do the real heavy lifting.
  265. def _findOne(self, method, name, attrs, text, **kwargs):
  266. r = None
  267. l = method(name, attrs, text, 1, **kwargs)
  268. if l:
  269. r = l[0]
  270. return r
  271. def _findAll(self, name, attrs, text, limit, generator, **kwargs):
  272. "Iterates over a generator looking for things that match."
  273. if isinstance(name, SoupStrainer):
  274. strainer = name
  275. else:
  276. # Build a SoupStrainer
  277. strainer = SoupStrainer(name, attrs, text, **kwargs)
  278. results = ResultSet(strainer)
  279. g = generator()
  280. while True:
  281. try:
  282. i = next(g)
  283. except StopIteration:
  284. break
  285. if i:
  286. found = strainer.search(i)
  287. if found:
  288. results.append(found)
  289. if limit and len(results) >= limit:
  290. break
  291. return results
  292. #These Generators can be used to navigate starting from both
  293. #NavigableStrings and Tags.
  294. def nextGenerator(self):
  295. i = self
  296. while i:
  297. i = i.__next__
  298. yield i
  299. def nextSiblingGenerator(self):
  300. i = self
  301. while i:
  302. i = i.nextSibling
  303. yield i
  304. def previousGenerator(self):
  305. i = self
  306. while i:
  307. i = i.previous
  308. yield i
  309. def previousSiblingGenerator(self):
  310. i = self
  311. while i:
  312. i = i.previousSibling
  313. yield i
  314. def parentGenerator(self):
  315. i = self
  316. while i:
  317. i = i.parent
  318. yield i
  319. # Utility methods
  320. def substituteEncoding(self, str, encoding=None):
  321. encoding = encoding or "utf-8"
  322. return str.replace("%SOUP-ENCODING%", encoding)
  323. def toEncoding(self, s, encoding=None):
  324. """Encodes an object to a string in some encoding, or to Unicode.
  325. ."""
  326. if isinstance(s, str):
  327. if encoding:
  328. s = s.encode(encoding)
  329. elif isinstance(s, str):
  330. if encoding:
  331. s = s.encode(encoding)
  332. else:
  333. s = str(s)
  334. else:
  335. if encoding:
  336. s = self.toEncoding(str(s), encoding)
  337. else:
  338. s = str(s)
  339. return s
  340. class NavigableString(str, PageElement):
  341. def __new__(cls, value):
  342. """Create a new NavigableString.
  343. When unpickling a NavigableString, this method is called with
  344. the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
  345. passed in to the superclass's __new__ or the superclass won't know
  346. how to handle non-ASCII characters.
  347. """
  348. if isinstance(value, str):
  349. return str.__new__(cls, value)
  350. return str.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
  351. def __getnewargs__(self):
  352. return (str(self),)
  353. def __getattr__(self, attr):
  354. """text.string gives you text. This is for backwards
  355. compatibility for Navigable*String, but for CData* it lets you
  356. get the string without the CData wrapper."""
  357. if attr == 'string':
  358. return self
  359. else:
  360. raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, attr))
  361. def encode(self, encoding=DEFAULT_OUTPUT_ENCODING):
  362. return self.decode().encode(encoding)
  363. def decodeGivenEventualEncoding(self, eventualEncoding):
  364. return self
  365. class CData(NavigableString):
  366. def decodeGivenEventualEncoding(self, eventualEncoding):
  367. return '<![CDATA[' + self + ']]>'
  368. class ProcessingInstruction(NavigableString):
  369. def decodeGivenEventualEncoding(self, eventualEncoding):
  370. output = self
  371. if '%SOUP-ENCODING%' in output:
  372. output = self.substituteEncoding(output, eventualEncoding)
  373. return '<?' + output + '?>'
  374. class Comment(NavigableString):
  375. def decodeGivenEventualEncoding(self, eventualEncoding):
  376. return '<!--' + self + '-->'
  377. class Declaration(NavigableString):
  378. def decodeGivenEventualEncoding(self, eventualEncoding):
  379. return '<!' + self + '>'
  380. class Tag(PageElement):
  381. """Represents a found HTML tag with its attributes and contents."""
  382. def _invert(h):
  383. "Cheap function to invert a hash."
  384. i = {}
  385. for k,v in list(h.items()):
  386. i[v] = k
  387. return i
  388. XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'",
  389. "quot" : '"',
  390. "amp" : "&",
  391. "lt" : "<",
  392. "gt" : ">" }
  393. XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS)
  394. def _convertEntities(self, match):
  395. """Used in a call to re.sub to replace HTML, XML, and numeric
  396. entities with the appropriate Unicode characters. If HTML
  397. entities are being converted, any unrecognized entities are
  398. escaped."""
  399. x = match.group(1)
  400. if self.convertHTMLEntities and x in name2codepoint:
  401. return chr(name2codepoint[x])
  402. elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS:
  403. if self.convertXMLEntities:
  404. return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]
  405. else:
  406. return '&%s;' % x
  407. elif len(x) > 0 and x[0] == '#':
  408. # Handle numeric entities
  409. if len(x) > 1 and x[1] == 'x':
  410. return chr(int(x[2:], 16))
  411. else:
  412. return chr(int(x[1:]))
  413. elif self.escapeUnrecognizedEntities:
  414. return '&amp;%s;' % x
  415. else:
  416. return '&%s;' % x
  417. def __init__(self, parser, name, attrs=None, parent=None,
  418. previous=None):
  419. "Basic constructor."
  420. # We don't actually store the parser object: that lets extracted
  421. # chunks be garbage-collected
  422. self.parserClass = parser.__class__
  423. self.isSelfClosing = parser.isSelfClosingTag(name)
  424. self.name = name
  425. if attrs == None:
  426. attrs = []
  427. self.attrs = attrs
  428. self.contents = []
  429. self.setup(parent, previous)
  430. self.hidden = False
  431. self.containsSubstitutions = False
  432. self.convertHTMLEntities = parser.convertHTMLEntities
  433. self.convertXMLEntities = parser.convertXMLEntities
  434. self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
  435. def convert(kval):
  436. "Converts HTML, XML and numeric entities in the attribute value."
  437. k, val = kval
  438. if val is None:
  439. return kval
  440. return (k, re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);",
  441. self._convertEntities, val))
  442. self.attrs = list(map(convert, self.attrs))
  443. def get(self, key, default=None):
  444. """Returns the value of the 'key' attribute for the tag, or
  445. the value given for 'default' if it doesn't have that
  446. attribute."""
  447. return self._getAttrMap().get(key, default)
  448. def has_key(self, key):
  449. return key in self._getAttrMap()
  450. def __getitem__(self, key):
  451. """tag[key] returns the value of the 'key' attribute for the tag,
  452. and throws an exception if it's not there."""
  453. return self._getAttrMap()[key]
  454. def __iter__(self):
  455. "Iterating over a tag iterates over its contents."
  456. return iter(self.contents)
  457. def __len__(self):
  458. "The length of a tag is the length of its list of contents."
  459. return len(self.contents)
  460. def __contains__(self, x):
  461. return x in self.contents
  462. def __bool__(self):
  463. "A tag is non-None even if it has no contents."
  464. return True
  465. def __setitem__(self, key, value):
  466. """Setting tag[key] sets the value of the 'key' attribute for the
  467. tag."""
  468. self._getAttrMap()
  469. self.attrMap[key] = value
  470. found = False
  471. for i in range(0, len(self.attrs)):
  472. if self.attrs[i][0] == key:
  473. self.attrs[i] = (key, value)
  474. found = True
  475. if not found:
  476. self.attrs.append((key, value))
  477. self._getAttrMap()[key] = value
  478. def __delitem__(self, key):
  479. "Deleting tag[key] deletes all 'key' attributes for the tag."
  480. for item in self.attrs:
  481. if item[0] == key:
  482. self.attrs.remove(item)
  483. #We don't break because bad HTML can define the same
  484. #attribute multiple times.
  485. self._getAttrMap()
  486. if key in self.attrMap:
  487. del self.attrMap[key]
  488. def __call__(self, *args, **kwargs):
  489. """Calling a tag like a function is the same as calling its
  490. findAll() method. Eg. tag('a') returns a list of all the A tags
  491. found within this tag."""
  492. return self.findAll(*args, **kwargs)
  493. def __getattr__(self, tag):
  494. #print "Getattr %s.%s" % (self.__class__, tag)
  495. if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3:
  496. return self.find(tag[:-3])
  497. elif tag.find('__') != 0:
  498. return self.find(tag)
  499. raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__, tag))
  500. def __eq__(self, other):
  501. """Returns true iff this tag has the same name, the same attributes,
  502. and the same contents (recursively) as the given tag.
  503. NOTE: right now this will return false if two tags have the
  504. same attributes in a different order. Should this be fixed?"""
  505. if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other):
  506. return False
  507. for i in range(0, len(self.contents)):
  508. if self.contents[i] != other.contents[i]:
  509. return False
  510. return True
  511. def __ne__(self, other):
  512. """Returns true iff this tag is not identical to the other tag,
  513. as defined in __eq__."""
  514. return not self == other
  515. def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
  516. """Renders this tag as a string."""
  517. return self.decode(eventualEncoding=encoding)
  518. BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|"
  519. + "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)"
  520. + ")")
  521. def _sub_entity(self, x):
  522. """Used with a regular expression to substitute the
  523. appropriate XML entity for an XML special character."""
  524. return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";"
  525. def __unicode__(self):
  526. return self.decode()
  527. def __str__(self):
  528. return self.encode()
  529. def encode(self, encoding=DEFAULT_OUTPUT_ENCODING,
  530. prettyPrint=False, indentLevel=0):
  531. return self.decode(prettyPrint, indentLevel, encoding).encode(encoding)
  532. def decode(self, prettyPrint=False, indentLevel=0,
  533. eventualEncoding=DEFAULT_OUTPUT_ENCODING):
  534. """Returns a string or Unicode representation of this tag and
  535. its contents. To get Unicode, pass None for encoding."""
  536. attrs = []
  537. if self.attrs:
  538. for key, val in self.attrs:
  539. fmt = '%s="%s"'
  540. if isString(val):
  541. if (self.containsSubstitutions
  542. and eventualEncoding is not None
  543. and '%SOUP-ENCODING%' in val):
  544. val = self.substituteEncoding(val, eventualEncoding)
  545. # The attribute value either:
  546. #
  547. # * Contains no embedded double quotes or single quotes.
  548. # No problem: we enclose it in double quotes.
  549. # * Contains embedded single quotes. No problem:
  550. # double quotes work here too.
  551. # * Contains embedded double quotes. No problem:
  552. # we enclose it in single quotes.
  553. # * Embeds both single _and_ double quotes. This
  554. # can't happen naturally, but it can happen if
  555. # you modify an attribute value after parsing
  556. # the document. Now we have a bit of a
  557. # problem. We solve it by enclosing the
  558. # attribute in single quotes, and escaping any
  559. # embedded single quotes to XML entities.
  560. if '"' in val:
  561. fmt = "%s='%s'"
  562. if "'" in val:
  563. # TODO: replace with apos when
  564. # appropriate.
  565. val = val.replace("'", "&squot;")
  566. # Now we're okay w/r/t quotes. But the attribute
  567. # value might also contain angle brackets, or
  568. # ampersands that aren't part of entities. We need
  569. # to escape those to XML entities too.
  570. val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val)
  571. if val is None:
  572. # Handle boolean attributes.
  573. decoded = key
  574. else:
  575. decoded = fmt % (key, val)
  576. attrs.append(decoded)
  577. close = ''
  578. closeTag = ''
  579. if self.isSelfClosing:
  580. close = ' /'
  581. else:
  582. closeTag = '</%s>' % self.name
  583. indentTag, indentContents = 0, 0
  584. if prettyPrint:
  585. indentTag = indentLevel
  586. space = (' ' * (indentTag-1))
  587. indentContents = indentTag + 1
  588. contents = self.decodeContents(prettyPrint, indentContents,
  589. eventualEncoding)
  590. if self.hidden:
  591. s = contents
  592. else:
  593. s = []
  594. attributeString = ''
  595. if attrs:
  596. attributeString = ' ' + ' '.join(attrs)
  597. if prettyPrint:
  598. s.append(space)
  599. s.append('<%s%s%s>' % (self.name, attributeString, close))
  600. if prettyPrint:
  601. s.append("\n")
  602. s.append(contents)
  603. if prettyPrint and contents and contents[-1] != "\n":
  604. s.append("\n")
  605. if prettyPrint and closeTag:
  606. s.append(space)
  607. s.append(closeTag)
  608. if prettyPrint and closeTag and self.nextSibling:
  609. s.append("\n")
  610. s = ''.join(s)
  611. return s
  612. def decompose(self):
  613. """Recursively destroys the contents of this tree."""
  614. contents = [i for i in self.contents]
  615. for i in contents:
  616. if isinstance(i, Tag):
  617. i.decompose()
  618. else:
  619. i.extract()
  620. self.extract()
  621. def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING):
  622. return self.encode(encoding, True)
  623. def encodeContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
  624. prettyPrint=False, indentLevel=0):
  625. return self.decodeContents(prettyPrint, indentLevel).encode(encoding)
  626. def decodeContents(self, prettyPrint=False, indentLevel=0,
  627. eventualEncoding=DEFAULT_OUTPUT_ENCODING):
  628. """Renders the contents of this tag as a string in the given
  629. encoding. If encoding is None, returns a Unicode string.."""
  630. s=[]
  631. for c in self:
  632. text = None
  633. if isinstance(c, NavigableString):
  634. text = c.decodeGivenEventualEncoding(eventualEncoding)
  635. elif isinstance(c, Tag):
  636. s.append(c.decode(prettyPrint, indentLevel, eventualEncoding))
  637. if text and prettyPrint:
  638. text = text.strip()
  639. if text:
  640. if prettyPrint:
  641. s.append(" " * (indentLevel-1))
  642. s.append(text)
  643. if prettyPrint:
  644. s.append("\n")
  645. return ''.join(s)
  646. #Soup methods
  647. def find(self, name=None, attrs={}, recursive=True, text=None,
  648. **kwargs):
  649. """Return only the first child of this Tag matching the given
  650. criteria."""
  651. r = None
  652. l = self.findAll(name, attrs, recursive, text, 1, **kwargs)
  653. if l:
  654. r = l[0]
  655. return r
  656. findChild = find
  657. def findAll(self, name=None, attrs={}, recursive=True, text=None,
  658. limit=None, **kwargs):
  659. """Extracts a list of Tag objects that match the given
  660. criteria. You can specify the name of the Tag and any
  661. attributes you want the Tag to have.
  662. The value of a key-value pair in the 'attrs' map can be a
  663. string, a list of strings, a regular expression object, or a
  664. callable that takes a string and returns whether or not the
  665. string matches for some custom definition of 'matches'. The
  666. same is true of the tag name."""
  667. generator = self.recursiveChildGenerator
  668. if not recursive:
  669. generator = self.childGenerator
  670. return self._findAll(name, attrs, text, limit, generator, **kwargs)
  671. findChildren = findAll
  672. # Pre-3.x compatibility methods. Will go away in 4.0.
  673. first = find
  674. fetch = findAll
  675. def fetchText(self, text=None, recursive=True, limit=None):
  676. return self.findAll(text=text, recursive=recursive, limit=limit)
  677. def firstText(self, text=None, recursive=True):
  678. return self.find(text=text, recursive=recursive)
  679. # 3.x compatibility methods. Will go away in 4.0.
  680. def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
  681. prettyPrint=False, indentLevel=0):
  682. if encoding is None:
  683. return self.decodeContents(prettyPrint, indentLevel, encoding)
  684. else:
  685. return self.encodeContents(encoding, prettyPrint, indentLevel)
  686. #Private methods
  687. def _getAttrMap(self):
  688. """Initializes a map representation of this tag's attributes,
  689. if not already initialized."""
  690. if not getattr(self, 'attrMap'):
  691. self.attrMap = {}
  692. for (key, value) in self.attrs:
  693. self.attrMap[key] = value
  694. return self.attrMap
  695. #Generator methods
  696. def recursiveChildGenerator(self):
  697. if not len(self.contents):
  698. raise StopIteration
  699. # This works around the bug referenced in
  700. # BeautifulSoup.py.3.diff that comes with BeautifulSoup by
  701. # hiding this line from 2to3's next-generator-method fixer.
  702. stopNode = getattr(self._lastRecursiveChild(), 'next')
  703. current = self.contents[0]
  704. while current is not stopNode:
  705. yield current
  706. current = getattr(current, 'next')
  707. def childGenerator(self):
  708. if not len(self.contents):
  709. raise StopIteration
  710. current = self.contents[0]
  711. while current:
  712. yield current
  713. current = current.nextSibling
  714. raise StopIteration
  715. # Next, a couple classes to represent queries and their results.
  716. class SoupStrainer:
  717. """Encapsulates a number of ways of matching a markup element (tag or
  718. text)."""
  719. def __init__(self, name=None, attrs={}, text=None, **kwargs):
  720. self.name = name
  721. if isString(attrs):
  722. kwargs['class'] = attrs
  723. attrs = None
  724. if kwargs:
  725. if attrs:
  726. attrs = attrs.copy()
  727. attrs.update(kwargs)
  728. else:
  729. attrs = kwargs
  730. self.attrs = attrs
  731. self.text = text
  732. def __str__(self):
  733. if self.text:
  734. return self.text
  735. else:
  736. return "%s|%s" % (self.name, self.attrs)
  737. def searchTag(self, markupName=None, markupAttrs={}):
  738. found = None
  739. markup = None
  740. if isinstance(markupName, Tag):
  741. markup = markupName
  742. markupAttrs = markup
  743. callFunctionWithTagData = hasattr(self.name, '__call__') \
  744. and not isinstance(markupName, Tag)
  745. if (not self.name) \
  746. or callFunctionWithTagData \
  747. or (markup and self._matches(markup, self.name)) \
  748. or (not markup and self._matches(markupName, self.name)):
  749. if callFunctionWithTagData:
  750. match = self.name(markupName, markupAttrs)
  751. else:
  752. match = True
  753. markupAttrMap = None
  754. for attr, matchAgainst in list(self.attrs.items()):
  755. if not markupAttrMap:
  756. if hasattr(markupAttrs, 'get'):
  757. markupAttrMap = markupAttrs
  758. else:
  759. markupAttrMap = {}
  760. for k,v in markupAttrs:
  761. markupAttrMap[k] = v
  762. attrValue = markupAttrMap.get(attr)
  763. if not self._matches(attrValue, matchAgainst):
  764. match = False
  765. break
  766. if match:
  767. if markup:
  768. found = markup
  769. else:
  770. found = markupName
  771. return found
  772. def search(self, markup):
  773. #print 'looking for %s in %s' % (self, markup)
  774. found = None
  775. # If given a list of items, scan it for a text element that
  776. # matches.
  777. if isList(markup) and not isinstance(markup, Tag):
  778. for element in markup:
  779. if isinstance(element, NavigableString) \
  780. and self.search(element):
  781. found = element
  782. break
  783. # If it's a Tag, make sure its name or attributes match.
  784. # Don't bother with Tags if we're searching for text.
  785. elif isinstance(markup, Tag):
  786. if not self.text:
  787. found = self.searchTag(markup)
  788. # If it's text, make sure the text matches.
  789. elif isinstance(markup, NavigableString) or \
  790. isString(markup):
  791. if self._matches(markup, self.text):
  792. found = markup
  793. else:
  794. raise Exception("I don't know how to match against a %s" \
  795. % markup.__class__)
  796. return found
  797. def _matches(self, markup, matchAgainst):
  798. #print "Matching %s against %s" % (markup, matchAgainst)
  799. result = False
  800. if matchAgainst == True and type(matchAgainst) == bool:
  801. result = markup != None
  802. elif hasattr(matchAgainst, '__call__'):
  803. result = matchAgainst(markup)
  804. else:
  805. #Custom match methods take the tag as an argument, but all
  806. #other ways of matching match the tag name as a string.
  807. if isinstance(markup, Tag):
  808. markup = markup.name
  809. if markup is not None and not isString(markup):
  810. markup = str(markup)
  811. #Now we know that chunk is either a string, or None.
  812. if hasattr(matchAgainst, 'match'):
  813. # It's a regexp object.
  814. result = markup and matchAgainst.search(markup)
  815. elif (isList(matchAgainst)
  816. and (markup is not None or not isString(matchAgainst))):
  817. result = markup in matchAgainst
  818. elif hasattr(matchAgainst, 'items'):
  819. result = matchAgainst in markup
  820. elif matchAgainst and isString(markup):
  821. if isinstance(markup, str):
  822. matchAgainst = str(matchAgainst)
  823. else:
  824. matchAgainst = str(matchAgainst)
  825. if not result:
  826. result = matchAgainst == markup
  827. return result
  828. class ResultSet(list):
  829. """A ResultSet is just a list that keeps track of the SoupStrainer
  830. that created it."""
  831. def __init__(self, source):
  832. list.__init__([])
  833. self.source = source
  834. # Now, some helper functions.
  835. def isList(l):
  836. """Convenience method that works with all 2.x versions of Python
  837. to determine whether or not something is listlike."""
  838. return ((hasattr(l, '__iter__') and not isString(l))
  839. or (type(l) in (list, tuple)))
  840. def isString(s):
  841. """Convenience method that works with all 2.x versions of Python
  842. to determine whether or not something is stringlike."""
  843. try:
  844. return isinstance(s, str) or isinstance(s, str)
  845. except NameError:
  846. return isinstance(s, str)
  847. def buildTagMap(default, *args):
  848. """Turns a list of maps, lists, or scalars into a single map.
  849. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and
  850. NESTING_RESET_TAGS maps out of lists and partial maps."""
  851. built = {}
  852. for portion in args:
  853. if hasattr(portion, 'items'):
  854. #It's a map. Merge it.
  855. for k,v in list(portion.items()):
  856. built[k] = v
  857. elif isList(portion) and not isString(portion):
  858. #It's a list. Map each item to the default.
  859. for k in portion:
  860. built[k] = default
  861. else:
  862. #It's a scalar. Map it to the default.
  863. built[portion] = default
  864. return built
  865. # Now, the parser classes.
  866. class HTMLParserBuilder(HTMLParser):
  867. def __init__(self, soup):
  868. HTMLParser.__init__(self)
  869. self.soup = soup
  870. # We inherit feed() and reset().
  871. def handle_starttag(self, name, attrs):
  872. if name == 'meta':
  873. self.soup.extractCharsetFromMeta(attrs)
  874. else:
  875. self.soup.unknown_starttag(name, attrs)
  876. def handle_endtag(self, name):
  877. self.soup.unknown_endtag(name)
  878. def handle_data(self, content):
  879. self.soup.handle_data(content)
  880. def _toStringSubclass(self, text, subclass):
  881. """Adds a certain piece of text to the tree as a NavigableString
  882. subclass."""
  883. self.soup.endData()
  884. self.handle_data(text)
  885. self.soup.endData(subclass)
  886. def handle_pi(self, text):
  887. """Handle a processing instruction as a ProcessingInstruction
  888. object, possibly one with a %SOUP-ENCODING% slot into which an
  889. encoding will be plugged later."""
  890. if text[:3] == "xml":
  891. text = "xml version='1.0' encoding='%SOUP-ENCODING%'"
  892. self._toStringSubclass(text, ProcessingInstruction)
  893. def handle_comment(self, text):
  894. "Handle comments as Comment objects."
  895. self._toStringSubclass(text, Comment)
  896. def handle_charref(self, ref):
  897. "Handle character references as data."
  898. if self.soup.convertEntities:
  899. data = chr(int(ref))
  900. else:
  901. data = '&#%s;' % ref
  902. self.handle_data(data)
  903. def handle_entityref(self, ref):
  904. """Handle entity references as data, possibly converting known
  905. HTML and/or XML entity references to the corresponding Unicode
  906. characters."""
  907. data = None
  908. if self.soup.convertHTMLEntities:
  909. try:
  910. data = chr(name2codepoint[ref])
  911. except KeyError:
  912. pass
  913. if not data and self.soup.convertXMLEntities:
  914. data = self.soup.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref)
  915. if not data and self.soup.convertHTMLEntities and \
  916. not self.soup.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref):
  917. # TODO: We've got a problem here. We're told this is
  918. # an entity reference, but it's not an XML entity
  919. # reference or an HTML entity reference. Nonetheless,
  920. # the logical thing to do is to pass it through as an
  921. # unrecognized entity reference.
  922. #
  923. # Except: when the input is "&carol;" this function
  924. # will be called with input "carol". When the input is
  925. # "AT&T", this function will be called with input
  926. # "T". We have no way of knowing whether a semicolon
  927. # was present originally, so we don't know whether
  928. # this is an unknown entity or just a misplaced
  929. # ampersand.
  930. #
  931. # The more common case is a misplaced ampersand, so I
  932. # escape the ampersand and omit the trailing semicolon.
  933. data = "&amp;%s" % ref
  934. if not data:
  935. # This case is different from the one above, because we
  936. # haven't already gone through a supposedly comprehensive
  937. # mapping of entities to Unicode characters. We might not
  938. # have gone through any mapping at all. So the chances are
  939. # very high that this is a real entity, and not a
  940. # misplaced ampersand.
  941. data = "&%s;" % ref
  942. self.handle_data(data)
  943. def handle_decl(self, data):
  944. "Handle DOCTYPEs and the like as Declaration objects."
  945. self._toStringSubclass(data, Declaration)
  946. def parse_declaration(self, i):
  947. """Treat a bogus SGML declaration as raw data. Treat a CDATA
  948. declaration as a CData object."""
  949. j = None
  950. if self.rawdata[i:i+9] == '<![CDATA[':
  951. k = self.rawdata.find(']]>', i)
  952. if k == -1:
  953. k = len(self.rawdata)
  954. data = self.rawdata[i+9:k]
  955. j = k+3
  956. self._toStringSubclass(data, CData)
  957. else:
  958. try:
  959. j = HTMLParser.parse_declaration(self, i)
  960. except HTMLParseError:
  961. toHandle = self.rawdata[i:]
  962. self.handle_data(toHandle)
  963. j = i + len(toHandle)
  964. return j
  965. class BeautifulStoneSoup(Tag):
  966. """This class contains the basic parser and search code. It defines
  967. a parser that knows nothing about tag behavior except for the
  968. following:
  969. You can't close a tag without closing all the tags it encloses.
  970. That is, "<foo><bar></foo>" actually means
  971. "<foo><bar></bar></foo>".
  972. [Another possible explanation is "<foo><bar /></foo>", but since
  973. this class defines no SELF_CLOSING_TAGS, it will never use that
  974. explanation.]
  975. This class is useful for parsing XML or made-up markup languages,
  976. or when BeautifulSoup makes an assumption counter to what you were
  977. expecting."""
  978. SELF_CLOSING_TAGS = {}
  979. NESTABLE_TAGS = {}
  980. RESET_NESTING_TAGS = {}
  981. QUOTE_TAGS = {}
  982. PRESERVE_WHITESPACE_TAGS = []
  983. MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'),
  984. lambda x: x.group(1) + ' />'),
  985. (re.compile('<!\s+([^<>]*)>'),
  986. lambda x: '<!' + x.group(1) + '>')
  987. ]
  988. ROOT_TAG_NAME = '[document]'
  989. HTML_ENTITIES = "html"
  990. XML_ENTITIES = "xml"
  991. XHTML_ENTITIES = "xhtml"
  992. # TODO: This only exists for backwards-compatibility
  993. ALL_ENTITIES = XHTML_ENTITIES
  994. # Used when determining whether a text node is all whitespace and
  995. # can be replaced with a single space. A text node that contains
  996. # fancy Unicode spaces (usually non-breaking) should be left
  997. # alone.
  998. STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, }
  999. def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None,
  1000. markupMassage=True, smartQuotesTo=XML_ENTITIES,
  1001. convertEntities=None, selfClosingTags=None, isHTML=False,
  1002. builder=HTMLParserBuilder):
  1003. """The Soup object is initialized as the 'root tag', and the
  1004. provided markup (which can be a string or a file-like object)
  1005. is fed into the underlying parser.
  1006. HTMLParser will process most bad HTML, and the BeautifulSoup
  1007. class has some tricks for dealing with some HTML that kills
  1008. HTMLParser, but Beautiful Soup can nonetheless choke or lose data
  1009. if your data uses self-closing tags or declarations
  1010. incorrectly.
  1011. By default, Beautiful Soup uses regexes to sanitize input,
  1012. avoiding the vast majority of these problems. If the problems
  1013. don't apply to you, pass in False for markupMassage, and
  1014. you'll get better performance.
  1015. The default parser massage techniques fix the two most common
  1016. instances of invalid HTML that choke HTMLParser:
  1017. <br/> (No space between name of closing tag and tag close)
  1018. <! --Comment--> (Extraneous whitespace in declaration)
  1019. You can pass in a custom list of (RE object, replace method)
  1020. tuples to get Beautiful Soup to scrub your input the way you
  1021. want."""
  1022. self.parseOnlyThese = parseOnlyThese
  1023. self.fromEncoding = fromEncoding
  1024. self.smartQuotesTo = smartQuotesTo
  1025. self.convertEntities = convertEntities
  1026. # Set the rules for how we'll deal with the entities we
  1027. # encounter
  1028. if self.convertEntities:
  1029. # It doesn't make sense to convert encoded characters to
  1030. # entities even while you're converting entities to Unicode.
  1031. # Just convert it all to Unicode.
  1032. self.smartQuotesTo = None
  1033. if convertEntities == self.HTML_ENTITIES:
  1034. self.convertXMLEntities = False
  1035. self.convertHTMLEntities = True
  1036. self.escapeUnrecognizedEntities = True
  1037. elif convertEntities == self.XHTML_ENTITIES:
  1038. self.convertXMLEntities = True
  1039. self.convertHTMLEntities = True
  1040. self.escapeUnrecognizedEntities = False
  1041. elif convertEntities == self.XML_ENTITIES:
  1042. self.convertXMLEntities = True
  1043. self.convertHTMLEntities = False
  1044. self.escapeUnrecognizedEntities = False
  1045. else:
  1046. self.convertXMLEntities = False
  1047. self.convertHTMLEntities = False
  1048. self.escapeUnrecognizedEntities = False
  1049. self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
  1050. self.builder = builder(self)
  1051. self.reset()
  1052. if hasattr(markup, 'read'): # It's a file-type object.
  1053. markup = markup.read()
  1054. self.markup = markup
  1055. self.markupMassage = markupMassage
  1056. try:
  1057. self._feed(isHTML=isHTML)
  1058. except StopParsing:
  1059. pass
  1060. self.markup = None # The markup can now be GCed.
  1061. self.builder = None # So can the builder.
  1062. def _feed(self, inDocumentEncoding=None, isHTML=False):
  1063. # Convert the document to Unicode.
  1064. markup = self.markup
  1065. if isinstance(markup, str):
  1066. if not hasattr(self, 'originalEncoding'):
  1067. self.originalEncoding = None
  1068. else:
  1069. dammit = UnicodeDammit\
  1070. (markup, [self.fromEncoding, inDocumentEncoding],
  1071. smartQuotesTo=self.smartQuotesTo, isHTML=isHTML)
  1072. markup = dammit.str
  1073. self.originalEncoding = dammit.originalEncoding
  1074. self.declaredHTMLEncoding = dammit.declaredHTMLEncoding
  1075. if markup:
  1076. if self.markupMassage:
  1077. if not isList(self.markupMassage):
  1078. self.markupMassage = self.MARKUP_MASSAGE
  1079. for fix, m in self.markupMassage:
  1080. markup = fix.sub(m, markup)
  1081. # TODO: We get rid of markupMassage so that the
  1082. # soup object can be deepcopied later on. Some
  1083. # Python installations can't copy regexes. If anyone
  1084. # was relying on the existence of markupMassage, this
  1085. # might cause problems.
  1086. del(self.markupMassage)
  1087. self.builder.reset()
  1088. self.builder.feed(markup)
  1089. # Close out any unfinished strings and close all the open tags.
  1090. self.endData()
  1091. while self.currentTag.name != self.ROOT_TAG_NAME:
  1092. self.popTag()
  1093. def isSelfClosingTag(self, name):
  1094. """Returns true iff the given string is the name of a
  1095. self-closing tag according to this parser."""
  1096. return name in self.SELF_CLOSING_TAGS \
  1097. or name in self.instanceSelfClosingTags
  1098. def reset(self):
  1099. Tag.__init__(self, self, self.ROOT_TAG_NAME)
  1100. self.hidden = 1
  1101. self.builder.reset()
  1102. self.currentData = []
  1103. self.currentTag = None
  1104. self.tagStack = []
  1105. self.quoteStack = []
  1106. self.pushTag(self)
  1107. def popTag(self):
  1108. tag = self.tagStack.pop()
  1109. # Tags with just one string-owning child get the child as a
  1110. # 'string' property, so that soup.tag.string is shorthand for
  1111. # soup.tag.contents[0]
  1112. if len(self.currentTag.contents) == 1 and \
  1113. isinstance(self.currentTag.contents[0], NavigableString):
  1114. self.currentTag.string = self.currentTag.contents[0]
  1115. #print "Pop", tag.name
  1116. if self.tagStack:
  1117. self.currentTag = self.tagStack[-1]
  1118. return self.currentTag
  1119. def pushTag(self, tag):
  1120. #print "Push", tag.name
  1121. if self.currentTag:
  1122. self.currentTag.contents.append(tag)
  1123. self.tagStack.append(tag)
  1124. self.currentTag = self.tagStack[-1]

Large files files are truncated, but you can click here to view the full file