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

/other/FetchData/mechanize/_beautifulsoup.py

http://github.com/jbeezley/wrf-fire
Python | 1080 lines | 1060 code | 14 blank | 6 comment | 11 complexity | 398c00dfe07906cfe30e244af37d1bda MD5 | raw file
Possible License(s): AGPL-1.0
  1. """Beautiful Soup
  2. Elixir and Tonic
  3. "The Screen-Scraper's Friend"
  4. v2.1.1
  5. http://www.crummy.com/software/BeautifulSoup/
  6. Beautiful Soup parses arbitrarily invalid XML- or HTML-like substance
  7. into a tree representation. It provides methods and Pythonic idioms
  8. that make it easy to search and modify the tree.
  9. A well-formed XML/HTML document will yield a well-formed data
  10. structure. An ill-formed XML/HTML document will yield a
  11. correspondingly ill-formed data structure. If your document is only
  12. locally well-formed, you can use this library to find and process the
  13. well-formed part of it. The BeautifulSoup class has heuristics for
  14. obtaining a sensible parse tree in the face of common HTML errors.
  15. Beautiful Soup has no external dependencies. It works with Python 2.2
  16. and up.
  17. Beautiful Soup defines classes for four different parsing strategies:
  18. * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific
  19. language that kind of looks like XML.
  20. * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid
  21. or invalid.
  22. * ICantBelieveItsBeautifulSoup, for parsing valid but bizarre HTML
  23. that trips up BeautifulSoup.
  24. * BeautifulSOAP, for making it easier to parse XML documents that use
  25. lots of subelements containing a single string, where you'd prefer
  26. they put that string into an attribute (such as SOAP messages).
  27. You can subclass BeautifulStoneSoup or BeautifulSoup to create a
  28. parsing strategy specific to an XML schema or a particular bizarre
  29. HTML document. Typically your subclass would just override
  30. SELF_CLOSING_TAGS and/or NESTABLE_TAGS.
  31. """ #"
  32. from __future__ import generators
  33. __author__ = "Leonard Richardson (leonardr@segfault.org)"
  34. __version__ = "2.1.1"
  35. __date__ = "$Date: 2004/10/18 00:14:20 $"
  36. __copyright__ = "Copyright (c) 2004-2005 Leonard Richardson"
  37. __license__ = "PSF"
  38. from sgmllib import SGMLParser, SGMLParseError
  39. import types
  40. import re
  41. import sgmllib
  42. #This code makes Beautiful Soup able to parse XML with namespaces
  43. sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
  44. class NullType(object):
  45. """Similar to NoneType with a corresponding singleton instance
  46. 'Null' that, unlike None, accepts any message and returns itself.
  47. Examples:
  48. >>> Null("send", "a", "message")("and one more",
  49. ... "and what you get still") is Null
  50. True
  51. """
  52. def __new__(cls): return Null
  53. def __call__(self, *args, **kwargs): return Null
  54. ## def __getstate__(self, *args): return Null
  55. def __getattr__(self, attr): return Null
  56. def __getitem__(self, item): return Null
  57. def __setattr__(self, attr, value): pass
  58. def __setitem__(self, item, value): pass
  59. def __len__(self): return 0
  60. # FIXME: is this a python bug? otherwise ``for x in Null: pass``
  61. # never terminates...
  62. def __iter__(self): return iter([])
  63. def __contains__(self, item): return False
  64. def __repr__(self): return "Null"
  65. Null = object.__new__(NullType)
  66. class PageElement:
  67. """Contains the navigational information for some part of the page
  68. (either a tag or a piece of text)"""
  69. def setup(self, parent=Null, previous=Null):
  70. """Sets up the initial relations between this element and
  71. other elements."""
  72. self.parent = parent
  73. self.previous = previous
  74. self.next = Null
  75. self.previousSibling = Null
  76. self.nextSibling = Null
  77. if self.parent and self.parent.contents:
  78. self.previousSibling = self.parent.contents[-1]
  79. self.previousSibling.nextSibling = self
  80. def findNext(self, name=None, attrs={}, text=None):
  81. """Returns the first item that matches the given criteria and
  82. appears after this Tag in the document."""
  83. return self._first(self.fetchNext, name, attrs, text)
  84. firstNext = findNext
  85. def fetchNext(self, name=None, attrs={}, text=None, limit=None):
  86. """Returns all items that match the given criteria and appear
  87. before after Tag in the document."""
  88. return self._fetch(name, attrs, text, limit, self.nextGenerator)
  89. def findNextSibling(self, name=None, attrs={}, text=None):
  90. """Returns the closest sibling to this Tag that matches the
  91. given criteria and appears after this Tag in the document."""
  92. return self._first(self.fetchNextSiblings, name, attrs, text)
  93. firstNextSibling = findNextSibling
  94. def fetchNextSiblings(self, name=None, attrs={}, text=None, limit=None):
  95. """Returns the siblings of this Tag that match the given
  96. criteria and appear after this Tag in the document."""
  97. return self._fetch(name, attrs, text, limit, self.nextSiblingGenerator)
  98. def findPrevious(self, name=None, attrs={}, text=None):
  99. """Returns the first item that matches the given criteria and
  100. appears before this Tag in the document."""
  101. return self._first(self.fetchPrevious, name, attrs, text)
  102. def fetchPrevious(self, name=None, attrs={}, text=None, limit=None):
  103. """Returns all items that match the given criteria and appear
  104. before this Tag in the document."""
  105. return self._fetch(name, attrs, text, limit, self.previousGenerator)
  106. firstPrevious = findPrevious
  107. def findPreviousSibling(self, name=None, attrs={}, text=None):
  108. """Returns the closest sibling to this Tag that matches the
  109. given criteria and appears before this Tag in the document."""
  110. return self._first(self.fetchPreviousSiblings, name, attrs, text)
  111. firstPreviousSibling = findPreviousSibling
  112. def fetchPreviousSiblings(self, name=None, attrs={}, text=None,
  113. limit=None):
  114. """Returns the siblings of this Tag that match the given
  115. criteria and appear before this Tag in the document."""
  116. return self._fetch(name, attrs, text, limit,
  117. self.previousSiblingGenerator)
  118. def findParent(self, name=None, attrs={}):
  119. """Returns the closest parent of this Tag that matches the given
  120. criteria."""
  121. r = Null
  122. l = self.fetchParents(name, attrs, 1)
  123. if l:
  124. r = l[0]
  125. return r
  126. firstParent = findParent
  127. def fetchParents(self, name=None, attrs={}, limit=None):
  128. """Returns the parents of this Tag that match the given
  129. criteria."""
  130. return self._fetch(name, attrs, None, limit, self.parentGenerator)
  131. #These methods do the real heavy lifting.
  132. def _first(self, method, name, attrs, text):
  133. r = Null
  134. l = method(name, attrs, text, 1)
  135. if l:
  136. r = l[0]
  137. return r
  138. def _fetch(self, name, attrs, text, limit, generator):
  139. "Iterates over a generator looking for things that match."
  140. if not hasattr(attrs, 'items'):
  141. attrs = {'class' : attrs}
  142. results = []
  143. g = generator()
  144. while True:
  145. try:
  146. i = g.next()
  147. except StopIteration:
  148. break
  149. found = None
  150. if isinstance(i, Tag):
  151. if not text:
  152. if not name or self._matches(i, name):
  153. match = True
  154. for attr, matchAgainst in attrs.items():
  155. check = i.get(attr)
  156. if not self._matches(check, matchAgainst):
  157. match = False
  158. break
  159. if match:
  160. found = i
  161. elif text:
  162. if self._matches(i, text):
  163. found = i
  164. if found:
  165. results.append(found)
  166. if limit and len(results) >= limit:
  167. break
  168. return results
  169. #Generators that can be used to navigate starting from both
  170. #NavigableTexts and Tags.
  171. def nextGenerator(self):
  172. i = self
  173. while i:
  174. i = i.next
  175. yield i
  176. def nextSiblingGenerator(self):
  177. i = self
  178. while i:
  179. i = i.nextSibling
  180. yield i
  181. def previousGenerator(self):
  182. i = self
  183. while i:
  184. i = i.previous
  185. yield i
  186. def previousSiblingGenerator(self):
  187. i = self
  188. while i:
  189. i = i.previousSibling
  190. yield i
  191. def parentGenerator(self):
  192. i = self
  193. while i:
  194. i = i.parent
  195. yield i
  196. def _matches(self, chunk, howToMatch):
  197. #print 'looking for %s in %s' % (howToMatch, chunk)
  198. #
  199. # If given a list of items, return true if the list contains a
  200. # text element that matches.
  201. if isList(chunk) and not isinstance(chunk, Tag):
  202. for tag in chunk:
  203. if isinstance(tag, NavigableText) and self._matches(tag, howToMatch):
  204. return True
  205. return False
  206. if callable(howToMatch):
  207. return howToMatch(chunk)
  208. if isinstance(chunk, Tag):
  209. #Custom match methods take the tag as an argument, but all other
  210. #ways of matching match the tag name as a string
  211. chunk = chunk.name
  212. #Now we know that chunk is a string
  213. if not isinstance(chunk, basestring):
  214. chunk = str(chunk)
  215. if hasattr(howToMatch, 'match'):
  216. # It's a regexp object.
  217. return howToMatch.search(chunk)
  218. if isList(howToMatch):
  219. return chunk in howToMatch
  220. if hasattr(howToMatch, 'items'):
  221. return howToMatch.has_key(chunk)
  222. #It's just a string
  223. return str(howToMatch) == chunk
  224. class NavigableText(PageElement):
  225. def __getattr__(self, attr):
  226. "For backwards compatibility, text.string gives you text"
  227. if attr == 'string':
  228. return self
  229. else:
  230. raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
  231. class NavigableString(str, NavigableText):
  232. pass
  233. class NavigableUnicodeString(unicode, NavigableText):
  234. pass
  235. class Tag(PageElement):
  236. """Represents a found HTML tag with its attributes and contents."""
  237. def __init__(self, name, attrs=None, parent=Null, previous=Null):
  238. "Basic constructor."
  239. self.name = name
  240. if attrs == None:
  241. attrs = []
  242. self.attrs = attrs
  243. self.contents = []
  244. self.setup(parent, previous)
  245. self.hidden = False
  246. def get(self, key, default=None):
  247. """Returns the value of the 'key' attribute for the tag, or
  248. the value given for 'default' if it doesn't have that
  249. attribute."""
  250. return self._getAttrMap().get(key, default)
  251. def __getitem__(self, key):
  252. """tag[key] returns the value of the 'key' attribute for the tag,
  253. and throws an exception if it's not there."""
  254. return self._getAttrMap()[key]
  255. def __iter__(self):
  256. "Iterating over a tag iterates over its contents."
  257. return iter(self.contents)
  258. def __len__(self):
  259. "The length of a tag is the length of its list of contents."
  260. return len(self.contents)
  261. def __contains__(self, x):
  262. return x in self.contents
  263. def __nonzero__(self):
  264. "A tag is non-None even if it has no contents."
  265. return True
  266. def __setitem__(self, key, value):
  267. """Setting tag[key] sets the value of the 'key' attribute for the
  268. tag."""
  269. self._getAttrMap()
  270. self.attrMap[key] = value
  271. found = False
  272. for i in range(0, len(self.attrs)):
  273. if self.attrs[i][0] == key:
  274. self.attrs[i] = (key, value)
  275. found = True
  276. if not found:
  277. self.attrs.append((key, value))
  278. self._getAttrMap()[key] = value
  279. def __delitem__(self, key):
  280. "Deleting tag[key] deletes all 'key' attributes for the tag."
  281. for item in self.attrs:
  282. if item[0] == key:
  283. self.attrs.remove(item)
  284. #We don't break because bad HTML can define the same
  285. #attribute multiple times.
  286. self._getAttrMap()
  287. if self.attrMap.has_key(key):
  288. del self.attrMap[key]
  289. def __call__(self, *args, **kwargs):
  290. """Calling a tag like a function is the same as calling its
  291. fetch() method. Eg. tag('a') returns a list of all the A tags
  292. found within this tag."""
  293. return apply(self.fetch, args, kwargs)
  294. def __getattr__(self, tag):
  295. if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3:
  296. return self.first(tag[:-3])
  297. elif tag.find('__') != 0:
  298. return self.first(tag)
  299. def __eq__(self, other):
  300. """Returns true iff this tag has the same name, the same attributes,
  301. and the same contents (recursively) as the given tag.
  302. NOTE: right now this will return false if two tags have the
  303. same attributes in a different order. Should this be fixed?"""
  304. 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):
  305. return False
  306. for i in range(0, len(self.contents)):
  307. if self.contents[i] != other.contents[i]:
  308. return False
  309. return True
  310. def __ne__(self, other):
  311. """Returns true iff this tag is not identical to the other tag,
  312. as defined in __eq__."""
  313. return not self == other
  314. def __repr__(self):
  315. """Renders this tag as a string."""
  316. return str(self)
  317. def __unicode__(self):
  318. return self.__str__(1)
  319. def __str__(self, needUnicode=None, showStructureIndent=None):
  320. """Returns a string or Unicode representation of this tag and
  321. its contents.
  322. NOTE: since Python's HTML parser consumes whitespace, this
  323. method is not certain to reproduce the whitespace present in
  324. the original string."""
  325. attrs = []
  326. if self.attrs:
  327. for key, val in self.attrs:
  328. attrs.append('%s="%s"' % (key, val))
  329. close = ''
  330. closeTag = ''
  331. if self.isSelfClosing():
  332. close = ' /'
  333. else:
  334. closeTag = '</%s>' % self.name
  335. indentIncrement = None
  336. if showStructureIndent != None:
  337. indentIncrement = showStructureIndent
  338. if not self.hidden:
  339. indentIncrement += 1
  340. contents = self.renderContents(indentIncrement, needUnicode=needUnicode)
  341. if showStructureIndent:
  342. space = '\n%s' % (' ' * showStructureIndent)
  343. if self.hidden:
  344. s = contents
  345. else:
  346. s = []
  347. attributeString = ''
  348. if attrs:
  349. attributeString = ' ' + ' '.join(attrs)
  350. if showStructureIndent:
  351. s.append(space)
  352. s.append('<%s%s%s>' % (self.name, attributeString, close))
  353. s.append(contents)
  354. if closeTag and showStructureIndent != None:
  355. s.append(space)
  356. s.append(closeTag)
  357. s = ''.join(s)
  358. isUnicode = type(s) == types.UnicodeType
  359. if needUnicode and not isUnicode:
  360. s = unicode(s)
  361. elif isUnicode and needUnicode==False:
  362. s = str(s)
  363. return s
  364. def prettify(self, needUnicode=None):
  365. return self.__str__(needUnicode, showStructureIndent=True)
  366. def renderContents(self, showStructureIndent=None, needUnicode=None):
  367. """Renders the contents of this tag as a (possibly Unicode)
  368. string."""
  369. s=[]
  370. for c in self:
  371. text = None
  372. if isinstance(c, NavigableUnicodeString) or type(c) == types.UnicodeType:
  373. text = unicode(c)
  374. elif isinstance(c, Tag):
  375. s.append(c.__str__(needUnicode, showStructureIndent))
  376. elif needUnicode:
  377. text = unicode(c)
  378. else:
  379. text = str(c)
  380. if text:
  381. if showStructureIndent != None:
  382. if text[-1] == '\n':
  383. text = text[:-1]
  384. s.append(text)
  385. return ''.join(s)
  386. #Soup methods
  387. def firstText(self, text, recursive=True):
  388. """Convenience method to retrieve the first piece of text matching the
  389. given criteria. 'text' can be a string, a regular expression object,
  390. a callable that takes a string and returns whether or not the
  391. string 'matches', etc."""
  392. return self.first(recursive=recursive, text=text)
  393. def fetchText(self, text, recursive=True, limit=None):
  394. """Convenience method to retrieve all pieces of text matching the
  395. given criteria. 'text' can be a string, a regular expression object,
  396. a callable that takes a string and returns whether or not the
  397. string 'matches', etc."""
  398. return self.fetch(recursive=recursive, text=text, limit=limit)
  399. def first(self, name=None, attrs={}, recursive=True, text=None):
  400. """Return only the first child of this
  401. Tag matching the given criteria."""
  402. r = Null
  403. l = self.fetch(name, attrs, recursive, text, 1)
  404. if l:
  405. r = l[0]
  406. return r
  407. findChild = first
  408. def fetch(self, name=None, attrs={}, recursive=True, text=None,
  409. limit=None):
  410. """Extracts a list of Tag objects that match the given
  411. criteria. You can specify the name of the Tag and any
  412. attributes you want the Tag to have.
  413. The value of a key-value pair in the 'attrs' map can be a
  414. string, a list of strings, a regular expression object, or a
  415. callable that takes a string and returns whether or not the
  416. string matches for some custom definition of 'matches'. The
  417. same is true of the tag name."""
  418. generator = self.recursiveChildGenerator
  419. if not recursive:
  420. generator = self.childGenerator
  421. return self._fetch(name, attrs, text, limit, generator)
  422. fetchChildren = fetch
  423. #Utility methods
  424. def isSelfClosing(self):
  425. """Returns true iff this is a self-closing tag as defined in the HTML
  426. standard.
  427. TODO: This is specific to BeautifulSoup and its subclasses, but it's
  428. used by __str__"""
  429. return self.name in BeautifulSoup.SELF_CLOSING_TAGS
  430. def append(self, tag):
  431. """Appends the given tag to the contents of this tag."""
  432. self.contents.append(tag)
  433. #Private methods
  434. def _getAttrMap(self):
  435. """Initializes a map representation of this tag's attributes,
  436. if not already initialized."""
  437. if not getattr(self, 'attrMap'):
  438. self.attrMap = {}
  439. for (key, value) in self.attrs:
  440. self.attrMap[key] = value
  441. return self.attrMap
  442. #Generator methods
  443. def childGenerator(self):
  444. for i in range(0, len(self.contents)):
  445. yield self.contents[i]
  446. raise StopIteration
  447. def recursiveChildGenerator(self):
  448. stack = [(self, 0)]
  449. while stack:
  450. tag, start = stack.pop()
  451. if isinstance(tag, Tag):
  452. for i in range(start, len(tag.contents)):
  453. a = tag.contents[i]
  454. yield a
  455. if isinstance(a, Tag) and tag.contents:
  456. if i < len(tag.contents) - 1:
  457. stack.append((tag, i+1))
  458. stack.append((a, 0))
  459. break
  460. raise StopIteration
  461. def isList(l):
  462. """Convenience method that works with all 2.x versions of Python
  463. to determine whether or not something is listlike."""
  464. return hasattr(l, '__iter__') \
  465. or (type(l) in (types.ListType, types.TupleType))
  466. def buildTagMap(default, *args):
  467. """Turns a list of maps, lists, or scalars into a single map.
  468. Used to build the SELF_CLOSING_TAGS and NESTABLE_TAGS maps out
  469. of lists and partial maps."""
  470. built = {}
  471. for portion in args:
  472. if hasattr(portion, 'items'):
  473. #It's a map. Merge it.
  474. for k,v in portion.items():
  475. built[k] = v
  476. elif isList(portion):
  477. #It's a list. Map each item to the default.
  478. for k in portion:
  479. built[k] = default
  480. else:
  481. #It's a scalar. Map it to the default.
  482. built[portion] = default
  483. return built
  484. class BeautifulStoneSoup(Tag, SGMLParser):
  485. """This class contains the basic parser and fetch code. It defines
  486. a parser that knows nothing about tag behavior except for the
  487. following:
  488. You can't close a tag without closing all the tags it encloses.
  489. That is, "<foo><bar></foo>" actually means
  490. "<foo><bar></bar></foo>".
  491. [Another possible explanation is "<foo><bar /></foo>", but since
  492. this class defines no SELF_CLOSING_TAGS, it will never use that
  493. explanation.]
  494. This class is useful for parsing XML or made-up markup languages,
  495. or when BeautifulSoup makes an assumption counter to what you were
  496. expecting."""
  497. SELF_CLOSING_TAGS = {}
  498. NESTABLE_TAGS = {}
  499. RESET_NESTING_TAGS = {}
  500. QUOTE_TAGS = {}
  501. #As a public service we will by default silently replace MS smart quotes
  502. #and similar characters with their HTML or ASCII equivalents.
  503. MS_CHARS = { '\x80' : '&euro;',
  504. '\x81' : ' ',
  505. '\x82' : '&sbquo;',
  506. '\x83' : '&fnof;',
  507. '\x84' : '&bdquo;',
  508. '\x85' : '&hellip;',
  509. '\x86' : '&dagger;',
  510. '\x87' : '&Dagger;',
  511. '\x88' : '&caret;',
  512. '\x89' : '%',
  513. '\x8A' : '&Scaron;',
  514. '\x8B' : '&lt;',
  515. '\x8C' : '&OElig;',
  516. '\x8D' : '?',
  517. '\x8E' : 'Z',
  518. '\x8F' : '?',
  519. '\x90' : '?',
  520. '\x91' : '&lsquo;',
  521. '\x92' : '&rsquo;',
  522. '\x93' : '&ldquo;',
  523. '\x94' : '&rdquo;',
  524. '\x95' : '&bull;',
  525. '\x96' : '&ndash;',
  526. '\x97' : '&mdash;',
  527. '\x98' : '&tilde;',
  528. '\x99' : '&trade;',
  529. '\x9a' : '&scaron;',
  530. '\x9b' : '&gt;',
  531. '\x9c' : '&oelig;',
  532. '\x9d' : '?',
  533. '\x9e' : 'z',
  534. '\x9f' : '&Yuml;',}
  535. PARSER_MASSAGE = [(re.compile('(<[^<>]*)/>'),
  536. lambda(x):x.group(1) + ' />'),
  537. (re.compile('<!\s+([^<>]*)>'),
  538. lambda(x):'<!' + x.group(1) + '>'),
  539. (re.compile("([\x80-\x9f])"),
  540. lambda(x): BeautifulStoneSoup.MS_CHARS.get(x.group(1)))
  541. ]
  542. ROOT_TAG_NAME = '[document]'
  543. def __init__(self, text=None, avoidParserProblems=True,
  544. initialTextIsEverything=True):
  545. """Initialize this as the 'root tag' and feed in any text to
  546. the parser.
  547. NOTE about avoidParserProblems: sgmllib will process most bad
  548. HTML, and BeautifulSoup has tricks for dealing with some HTML
  549. that kills sgmllib, but Beautiful Soup can nonetheless choke
  550. or lose data if your data uses self-closing tags or
  551. declarations incorrectly. By default, Beautiful Soup sanitizes
  552. its input to avoid the vast majority of these problems. The
  553. problems are relatively rare, even in bad HTML, so feel free
  554. to pass in False to avoidParserProblems if they don't apply to
  555. you, and you'll get better performance. The only reason I have
  556. this turned on by default is so I don't get so many tech
  557. support questions.
  558. The two most common instances of invalid HTML that will choke
  559. sgmllib are fixed by the default parser massage techniques:
  560. <br/> (No space between name of closing tag and tag close)
  561. <! --Comment--> (Extraneous whitespace in declaration)
  562. You can pass in a custom list of (RE object, replace method)
  563. tuples to get Beautiful Soup to scrub your input the way you
  564. want."""
  565. Tag.__init__(self, self.ROOT_TAG_NAME)
  566. if avoidParserProblems \
  567. and not isList(avoidParserProblems):
  568. avoidParserProblems = self.PARSER_MASSAGE
  569. self.avoidParserProblems = avoidParserProblems
  570. SGMLParser.__init__(self)
  571. self.quoteStack = []
  572. self.hidden = 1
  573. self.reset()
  574. if hasattr(text, 'read'):
  575. #It's a file-type object.
  576. text = text.read()
  577. if text:
  578. self.feed(text)
  579. if initialTextIsEverything:
  580. self.done()
  581. def __getattr__(self, methodName):
  582. """This method routes method call requests to either the SGMLParser
  583. superclass or the Tag superclass, depending on the method name."""
  584. if methodName.find('start_') == 0 or methodName.find('end_') == 0 \
  585. or methodName.find('do_') == 0:
  586. return SGMLParser.__getattr__(self, methodName)
  587. elif methodName.find('__') != 0:
  588. return Tag.__getattr__(self, methodName)
  589. else:
  590. raise AttributeError
  591. def feed(self, text):
  592. if self.avoidParserProblems:
  593. for fix, m in self.avoidParserProblems:
  594. text = fix.sub(m, text)
  595. SGMLParser.feed(self, text)
  596. def done(self):
  597. """Called when you're done parsing, so that the unclosed tags can be
  598. correctly processed."""
  599. self.endData() #NEW
  600. while self.currentTag.name != self.ROOT_TAG_NAME:
  601. self.popTag()
  602. def reset(self):
  603. SGMLParser.reset(self)
  604. self.currentData = []
  605. self.currentTag = None
  606. self.tagStack = []
  607. self.pushTag(self)
  608. def popTag(self):
  609. tag = self.tagStack.pop()
  610. # Tags with just one string-owning child get the child as a
  611. # 'string' property, so that soup.tag.string is shorthand for
  612. # soup.tag.contents[0]
  613. if len(self.currentTag.contents) == 1 and \
  614. isinstance(self.currentTag.contents[0], NavigableText):
  615. self.currentTag.string = self.currentTag.contents[0]
  616. #print "Pop", tag.name
  617. if self.tagStack:
  618. self.currentTag = self.tagStack[-1]
  619. return self.currentTag
  620. def pushTag(self, tag):
  621. #print "Push", tag.name
  622. if self.currentTag:
  623. self.currentTag.append(tag)
  624. self.tagStack.append(tag)
  625. self.currentTag = self.tagStack[-1]
  626. def endData(self):
  627. currentData = ''.join(self.currentData)
  628. if currentData:
  629. if not currentData.strip():
  630. if '\n' in currentData:
  631. currentData = '\n'
  632. else:
  633. currentData = ' '
  634. c = NavigableString
  635. if type(currentData) == types.UnicodeType:
  636. c = NavigableUnicodeString
  637. o = c(currentData)
  638. o.setup(self.currentTag, self.previous)
  639. if self.previous:
  640. self.previous.next = o
  641. self.previous = o
  642. self.currentTag.contents.append(o)
  643. self.currentData = []
  644. def _popToTag(self, name, inclusivePop=True):
  645. """Pops the tag stack up to and including the most recent
  646. instance of the given tag. If inclusivePop is false, pops the tag
  647. stack up to but *not* including the most recent instqance of
  648. the given tag."""
  649. if name == self.ROOT_TAG_NAME:
  650. return
  651. numPops = 0
  652. mostRecentTag = None
  653. for i in range(len(self.tagStack)-1, 0, -1):
  654. if name == self.tagStack[i].name:
  655. numPops = len(self.tagStack)-i
  656. break
  657. if not inclusivePop:
  658. numPops = numPops - 1
  659. for i in range(0, numPops):
  660. mostRecentTag = self.popTag()
  661. return mostRecentTag
  662. def _smartPop(self, name):
  663. """We need to pop up to the previous tag of this type, unless
  664. one of this tag's nesting reset triggers comes between this
  665. tag and the previous tag of this type, OR unless this tag is a
  666. generic nesting trigger and another generic nesting trigger
  667. comes between this tag and the previous tag of this type.
  668. Examples:
  669. <p>Foo<b>Bar<p> should pop to 'p', not 'b'.
  670. <p>Foo<table>Bar<p> should pop to 'table', not 'p'.
  671. <p>Foo<table><tr>Bar<p> should pop to 'tr', not 'p'.
  672. <p>Foo<b>Bar<p> should pop to 'p', not 'b'.
  673. <li><ul><li> *<li>* should pop to 'ul', not the first 'li'.
  674. <tr><table><tr> *<tr>* should pop to 'table', not the first 'tr'
  675. <td><tr><td> *<td>* should pop to 'tr', not the first 'td'
  676. """
  677. nestingResetTriggers = self.NESTABLE_TAGS.get(name)
  678. isNestable = nestingResetTriggers != None
  679. isResetNesting = self.RESET_NESTING_TAGS.has_key(name)
  680. popTo = None
  681. inclusive = True
  682. for i in range(len(self.tagStack)-1, 0, -1):
  683. p = self.tagStack[i]
  684. if (not p or p.name == name) and not isNestable:
  685. #Non-nestable tags get popped to the top or to their
  686. #last occurance.
  687. popTo = name
  688. break
  689. if (nestingResetTriggers != None
  690. and p.name in nestingResetTriggers) \
  691. or (nestingResetTriggers == None and isResetNesting
  692. and self.RESET_NESTING_TAGS.has_key(p.name)):
  693. #If we encounter one of the nesting reset triggers
  694. #peculiar to this tag, or we encounter another tag
  695. #that causes nesting to reset, pop up to but not
  696. #including that tag.
  697. popTo = p.name
  698. inclusive = False
  699. break
  700. p = p.parent
  701. if popTo:
  702. self._popToTag(popTo, inclusive)
  703. def unknown_starttag(self, name, attrs, selfClosing=0):
  704. #print "Start tag %s" % name
  705. if self.quoteStack:
  706. #This is not a real tag.
  707. #print "<%s> is not real!" % name
  708. attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs))
  709. self.handle_data('<%s%s>' % (name, attrs))
  710. return
  711. self.endData()
  712. if not name in self.SELF_CLOSING_TAGS and not selfClosing:
  713. self._smartPop(name)
  714. tag = Tag(name, attrs, self.currentTag, self.previous)
  715. if self.previous:
  716. self.previous.next = tag
  717. self.previous = tag
  718. self.pushTag(tag)
  719. if selfClosing or name in self.SELF_CLOSING_TAGS:
  720. self.popTag()
  721. if name in self.QUOTE_TAGS:
  722. #print "Beginning quote (%s)" % name
  723. self.quoteStack.append(name)
  724. self.literal = 1
  725. def unknown_endtag(self, name):
  726. if self.quoteStack and self.quoteStack[-1] != name:
  727. #This is not a real end tag.
  728. #print "</%s> is not real!" % name
  729. self.handle_data('</%s>' % name)
  730. return
  731. self.endData()
  732. self._popToTag(name)
  733. if self.quoteStack and self.quoteStack[-1] == name:
  734. self.quoteStack.pop()
  735. self.literal = (len(self.quoteStack) > 0)
  736. def handle_data(self, data):
  737. self.currentData.append(data)
  738. def handle_pi(self, text):
  739. "Propagate processing instructions right through."
  740. self.handle_data("<?%s>" % text)
  741. def handle_comment(self, text):
  742. "Propagate comments right through."
  743. self.handle_data("<!--%s-->" % text)
  744. def handle_charref(self, ref):
  745. "Propagate char refs right through."
  746. self.handle_data('&#%s;' % ref)
  747. def handle_entityref(self, ref):
  748. "Propagate entity refs right through."
  749. self.handle_data('&%s;' % ref)
  750. def handle_decl(self, data):
  751. "Propagate DOCTYPEs and the like right through."
  752. self.handle_data('<!%s>' % data)
  753. def parse_declaration(self, i):
  754. """Treat a bogus SGML declaration as raw data. Treat a CDATA
  755. declaration as regular data."""
  756. j = None
  757. if self.rawdata[i:i+9] == '<![CDATA[':
  758. k = self.rawdata.find(']]>', i)
  759. if k == -1:
  760. k = len(self.rawdata)
  761. self.handle_data(self.rawdata[i+9:k])
  762. j = k+3
  763. else:
  764. try:
  765. j = SGMLParser.parse_declaration(self, i)
  766. except SGMLParseError:
  767. toHandle = self.rawdata[i:]
  768. self.handle_data(toHandle)
  769. j = i + len(toHandle)
  770. return j
  771. class BeautifulSoup(BeautifulStoneSoup):
  772. """This parser knows the following facts about HTML:
  773. * Some tags have no closing tag and should be interpreted as being
  774. closed as soon as they are encountered.
  775. * The text inside some tags (ie. 'script') may contain tags which
  776. are not really part of the document and which should be parsed
  777. as text, not tags. If you want to parse the text as tags, you can
  778. always fetch it and parse it explicitly.
  779. * Tag nesting rules:
  780. Most tags can't be nested at all. For instance, the occurance of
  781. a <p> tag should implicitly close the previous <p> tag.
  782. <p>Para1<p>Para2
  783. should be transformed into:
  784. <p>Para1</p><p>Para2
  785. Some tags can be nested arbitrarily. For instance, the occurance
  786. of a <blockquote> tag should _not_ implicitly close the previous
  787. <blockquote> tag.
  788. Alice said: <blockquote>Bob said: <blockquote>Blah
  789. should NOT be transformed into:
  790. Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah
  791. Some tags can be nested, but the nesting is reset by the
  792. interposition of other tags. For instance, a <tr> tag should
  793. implicitly close the previous <tr> tag within the same <table>,
  794. but not close a <tr> tag in another table.
  795. <table><tr>Blah<tr>Blah
  796. should be transformed into:
  797. <table><tr>Blah</tr><tr>Blah
  798. but,
  799. <tr>Blah<table><tr>Blah
  800. should NOT be transformed into
  801. <tr>Blah<table></tr><tr>Blah
  802. Differing assumptions about tag nesting rules are a major source
  803. of problems with the BeautifulSoup class. If BeautifulSoup is not
  804. treating as nestable a tag your page author treats as nestable,
  805. try ICantBelieveItsBeautifulSoup before writing your own
  806. subclass."""
  807. SELF_CLOSING_TAGS = buildTagMap(None, ['br' , 'hr', 'input', 'img', 'meta',
  808. 'spacer', 'link', 'frame', 'base'])
  809. QUOTE_TAGS = {'script': None}
  810. #According to the HTML standard, each of these inline tags can
  811. #contain another tag of the same type. Furthermore, it's common
  812. #to actually use these tags this way.
  813. NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup',
  814. 'center']
  815. #According to the HTML standard, these block tags can contain
  816. #another tag of the same type. Furthermore, it's common
  817. #to actually use these tags this way.
  818. NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
  819. #Lists can contain other lists, but there are restrictions.
  820. NESTABLE_LIST_TAGS = { 'ol' : [],
  821. 'ul' : [],
  822. 'li' : ['ul', 'ol'],
  823. 'dl' : [],
  824. 'dd' : ['dl'],
  825. 'dt' : ['dl'] }
  826. #Tables can contain other tables, but there are restrictions.
  827. NESTABLE_TABLE_TAGS = {'table' : [],
  828. 'tr' : ['table', 'tbody', 'tfoot', 'thead'],
  829. 'td' : ['tr'],
  830. 'th' : ['tr'],
  831. }
  832. NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre']
  833. #If one of these tags is encountered, all tags up to the next tag of
  834. #this type are popped.
  835. RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript',
  836. NON_NESTABLE_BLOCK_TAGS,
  837. NESTABLE_LIST_TAGS,
  838. NESTABLE_TABLE_TAGS)
  839. NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS,
  840. NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS)
  841. class ICantBelieveItsBeautifulSoup(BeautifulSoup):
  842. """The BeautifulSoup class is oriented towards skipping over
  843. common HTML errors like unclosed tags. However, sometimes it makes
  844. errors of its own. For instance, consider this fragment:
  845. <b>Foo<b>Bar</b></b>
  846. This is perfectly valid (if bizarre) HTML. However, the
  847. BeautifulSoup class will implicitly close the first b tag when it
  848. encounters the second 'b'. It will think the author wrote
  849. "<b>Foo<b>Bar", and didn't close the first 'b' tag, because
  850. there's no real-world reason to bold something that's already
  851. bold. When it encounters '</b></b>' it will close two more 'b'
  852. tags, for a grand total of three tags closed instead of two. This
  853. can throw off the rest of your document structure. The same is
  854. true of a number of other tags, listed below.
  855. It's much more common for someone to forget to close (eg.) a 'b'
  856. tag than to actually use nested 'b' tags, and the BeautifulSoup
  857. class handles the common case. This class handles the
  858. not-co-common case: where you can't believe someone wrote what
  859. they did, but it's valid HTML and BeautifulSoup screwed up by
  860. assuming it wouldn't be.
  861. If this doesn't do what you need, try subclassing this class or
  862. BeautifulSoup, and providing your own list of NESTABLE_TAGS."""
  863. I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \
  864. ['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong',
  865. 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b',
  866. 'big']
  867. I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript']
  868. NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS,
  869. I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS,
  870. I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS)
  871. class BeautifulSOAP(BeautifulStoneSoup):
  872. """This class will push a tag with only a single string child into
  873. the tag's parent as an attribute. The attribute's name is the tag
  874. name, and the value is the string child. An example should give
  875. the flavor of the change:
  876. <foo><bar>baz</bar></foo>
  877. =>
  878. <foo bar="baz"><bar>baz</bar></foo>
  879. You can then access fooTag['bar'] instead of fooTag.barTag.string.
  880. This is, of course, useful for scraping structures that tend to
  881. use subelements instead of attributes, such as SOAP messages. Note
  882. that it modifies its input, so don't print the modified version
  883. out.
  884. I'm not sure how many people really want to use this class; let me
  885. know if you do. Mainly I like the name."""
  886. def popTag(self):
  887. if len(self.tagStack) > 1:
  888. tag = self.tagStack[-1]
  889. parent = self.tagStack[-2]
  890. parent._getAttrMap()
  891. if (isinstance(tag, Tag) and len(tag.contents) == 1 and
  892. isinstance(tag.contents[0], NavigableText) and
  893. not parent.attrMap.has_key(tag.name)):
  894. parent[tag.name] = tag.contents[0]
  895. BeautifulStoneSoup.popTag(self)
  896. #Enterprise class names! It has come to our attention that some people
  897. #think the names of the Beautiful Soup parser classes are too silly
  898. #and "unprofessional" for use in enterprise screen-scraping. We feel
  899. #your pain! For such-minded folk, the Beautiful Soup Consortium And
  900. #All-Night Kosher Bakery recommends renaming this file to
  901. #"RobustParser.py" (or, in cases of extreme enterprisitude,
  902. #"RobustParserBeanInterface.class") and using the following
  903. #enterprise-friendly class aliases:
  904. class RobustXMLParser(BeautifulStoneSoup):
  905. pass
  906. class RobustHTMLParser(BeautifulSoup):
  907. pass
  908. class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup):
  909. pass
  910. class SimplifyingSOAPParser(BeautifulSOAP):
  911. pass
  912. ###
  913. #By default, act as an HTML pretty-printer.
  914. if __name__ == '__main__':
  915. import sys
  916. soup = BeautifulStoneSoup(sys.stdin.read())
  917. print soup.prettify()