PageRenderTime 70ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/SverigesTelevision/BeautifulSoup.py

http://xbmc-scripting.googlecode.com/
Python | 1812 lines | 1652 code | 76 blank | 84 comment | 105 complexity | c5294ca3eff11c63274843ef7a55d150 MD5 | raw file
Possible License(s): BSD-2-Clause

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

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

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