PageRenderTime 85ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/ng_mashup/static/js/openlayers/tools/BeautifulSoup.py

https://bitbucket.org/drnextgis/ng_mashup
Python | 1767 lines | 1627 code | 67 blank | 73 comment | 99 complexity | 714c47c0721c217f76e2a14493dea296 MD5 | raw file

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

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