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