PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/other/FetchData/BeautifulSoup.py

http://github.com/jbeezley/wrf-fire
Python | 2011 lines | 1871 code | 64 blank | 76 comment | 108 complexity | 06fc09a885b3590639d2138948a0f620 MD5 | raw file
Possible License(s): AGPL-1.0

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

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