PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/digsby/src/util/BeautifulSoup.py

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

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