element.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725
  1. __license__ = "MIT"
  2. from pdb import set_trace
  3. import collections
  4. import re
  5. import sys
  6. import warnings
  7. from bs4.dammit import EntitySubstitution
  8. DEFAULT_OUTPUT_ENCODING = "utf-8"
  9. PY3K = (sys.version_info[0] > 2)
  10. whitespace_re = re.compile("\s+")
  11. def _alias(attr):
  12. """Alias one attribute name to another for backward compatibility"""
  13. @property
  14. def alias(self):
  15. return getattr(self, attr)
  16. @alias.setter
  17. def alias(self):
  18. return setattr(self, attr)
  19. return alias
  20. class NamespacedAttribute(str):
  21. def __new__(cls, prefix, name, namespace=None):
  22. if name is None:
  23. obj = str.__new__(cls, prefix)
  24. elif prefix is None:
  25. # Not really namespaced.
  26. obj = str.__new__(cls, name)
  27. else:
  28. obj = str.__new__(cls, prefix + ":" + name)
  29. obj.prefix = prefix
  30. obj.name = name
  31. obj.namespace = namespace
  32. return obj
  33. class AttributeValueWithCharsetSubstitution(str):
  34. """A stand-in object for a character encoding specified in HTML."""
  35. class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution):
  36. """A generic stand-in for the value of a meta tag's 'charset' attribute.
  37. When Beautiful Soup parses the markup '<meta charset="utf8">', the
  38. value of the 'charset' attribute will be one of these objects.
  39. """
  40. def __new__(cls, original_value):
  41. obj = str.__new__(cls, original_value)
  42. obj.original_value = original_value
  43. return obj
  44. def encode(self, encoding):
  45. return encoding
  46. class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution):
  47. """A generic stand-in for the value of a meta tag's 'content' attribute.
  48. When Beautiful Soup parses the markup:
  49. <meta http-equiv="content-type" content="text/html; charset=utf8">
  50. The value of the 'content' attribute will be one of these objects.
  51. """
  52. CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M)
  53. def __new__(cls, original_value):
  54. match = cls.CHARSET_RE.search(original_value)
  55. if match is None:
  56. # No substitution necessary.
  57. return str.__new__(str, original_value)
  58. obj = str.__new__(cls, original_value)
  59. obj.original_value = original_value
  60. return obj
  61. def encode(self, encoding):
  62. def rewrite(match):
  63. return match.group(1) + encoding
  64. return self.CHARSET_RE.sub(rewrite, self.original_value)
  65. class HTMLAwareEntitySubstitution(EntitySubstitution):
  66. """Entity substitution rules that are aware of some HTML quirks.
  67. Specifically, the contents of <script> and <style> tags should not
  68. undergo entity substitution.
  69. Incoming NavigableString objects are checked to see if they're the
  70. direct children of a <script> or <style> tag.
  71. """
  72. cdata_containing_tags = set(["script", "style"])
  73. preformatted_tags = set(["pre"])
  74. @classmethod
  75. def _substitute_if_appropriate(cls, ns, f):
  76. if (isinstance(ns, NavigableString)
  77. and ns.parent is not None
  78. and ns.parent.name in cls.cdata_containing_tags):
  79. # Do nothing.
  80. return ns
  81. # Substitute.
  82. return f(ns)
  83. @classmethod
  84. def substitute_html(cls, ns):
  85. return cls._substitute_if_appropriate(
  86. ns, EntitySubstitution.substitute_html)
  87. @classmethod
  88. def substitute_xml(cls, ns):
  89. return cls._substitute_if_appropriate(
  90. ns, EntitySubstitution.substitute_xml)
  91. class PageElement(object):
  92. """Contains the navigational information for some part of the page
  93. (either a tag or a piece of text)"""
  94. # There are five possible values for the "formatter" argument passed in
  95. # to methods like encode() and prettify():
  96. #
  97. # "html" - All Unicode characters with corresponding HTML entities
  98. # are converted to those entities on output.
  99. # "minimal" - Bare ampersands and angle brackets are converted to
  100. # XML entities: &amp; &lt; &gt;
  101. # None - The null formatter. Unicode characters are never
  102. # converted to entities. This is not recommended, but it's
  103. # faster than "minimal".
  104. # A function - This function will be called on every string that
  105. # needs to undergo entity substitution.
  106. #
  107. # In an HTML document, the default "html" and "minimal" functions
  108. # will leave the contents of <script> and <style> tags alone. For
  109. # an XML document, all tags will be given the same treatment.
  110. HTML_FORMATTERS = {
  111. "html" : HTMLAwareEntitySubstitution.substitute_html,
  112. "minimal" : HTMLAwareEntitySubstitution.substitute_xml,
  113. None : None
  114. }
  115. XML_FORMATTERS = {
  116. "html" : EntitySubstitution.substitute_html,
  117. "minimal" : EntitySubstitution.substitute_xml,
  118. None : None
  119. }
  120. def format_string(self, s, formatter='minimal'):
  121. """Format the given string using the given formatter."""
  122. if not isinstance(formatter, collections.Callable):
  123. formatter = self._formatter_for_name(formatter)
  124. if formatter is None:
  125. output = s
  126. else:
  127. output = formatter(s)
  128. return output
  129. @property
  130. def _is_xml(self):
  131. """Is this element part of an XML tree or an HTML tree?
  132. This is used when mapping a formatter name ("minimal") to an
  133. appropriate function (one that performs entity-substitution on
  134. the contents of <script> and <style> tags, or not). It's
  135. inefficient, but it should be called very rarely.
  136. """
  137. if self.parent is None:
  138. # This is the top-level object. It should have .is_xml set
  139. # from tree creation. If not, take a guess--BS is usually
  140. # used on HTML markup.
  141. return getattr(self, 'is_xml', False)
  142. return self.parent._is_xml
  143. def _formatter_for_name(self, name):
  144. "Look up a formatter function based on its name and the tree."
  145. if self._is_xml:
  146. return self.XML_FORMATTERS.get(
  147. name, EntitySubstitution.substitute_xml)
  148. else:
  149. return self.HTML_FORMATTERS.get(
  150. name, HTMLAwareEntitySubstitution.substitute_xml)
  151. def setup(self, parent=None, previous_element=None, next_element=None,
  152. previous_sibling=None, next_sibling=None):
  153. """Sets up the initial relations between this element and
  154. other elements."""
  155. self.parent = parent
  156. self.previous_element = previous_element
  157. if previous_element is not None:
  158. self.previous_element.next_element = self
  159. self.next_element = next_element
  160. if self.next_element:
  161. self.next_element.previous_element = self
  162. self.next_sibling = next_sibling
  163. if self.next_sibling:
  164. self.next_sibling.previous_sibling = self
  165. if (not previous_sibling
  166. and self.parent is not None and self.parent.contents):
  167. previous_sibling = self.parent.contents[-1]
  168. self.previous_sibling = previous_sibling
  169. if previous_sibling:
  170. self.previous_sibling.next_sibling = self
  171. nextSibling = _alias("next_sibling") # BS3
  172. previousSibling = _alias("previous_sibling") # BS3
  173. def replace_with(self, replace_with):
  174. if not self.parent:
  175. raise ValueError(
  176. "Cannot replace one element with another when the"
  177. "element to be replaced is not part of a tree.")
  178. if replace_with is self:
  179. return
  180. if replace_with is self.parent:
  181. raise ValueError("Cannot replace a Tag with its parent.")
  182. old_parent = self.parent
  183. my_index = self.parent.index(self)
  184. self.extract()
  185. old_parent.insert(my_index, replace_with)
  186. return self
  187. replaceWith = replace_with # BS3
  188. def unwrap(self):
  189. my_parent = self.parent
  190. if not self.parent:
  191. raise ValueError(
  192. "Cannot replace an element with its contents when that"
  193. "element is not part of a tree.")
  194. my_index = self.parent.index(self)
  195. self.extract()
  196. for child in reversed(self.contents[:]):
  197. my_parent.insert(my_index, child)
  198. return self
  199. replace_with_children = unwrap
  200. replaceWithChildren = unwrap # BS3
  201. def wrap(self, wrap_inside):
  202. me = self.replace_with(wrap_inside)
  203. wrap_inside.append(me)
  204. return wrap_inside
  205. def extract(self):
  206. """Destructively rips this element out of the tree."""
  207. if self.parent is not None:
  208. del self.parent.contents[self.parent.index(self)]
  209. #Find the two elements that would be next to each other if
  210. #this element (and any children) hadn't been parsed. Connect
  211. #the two.
  212. last_child = self._last_descendant()
  213. next_element = last_child.next_element
  214. if (self.previous_element is not None and
  215. self.previous_element is not next_element):
  216. self.previous_element.next_element = next_element
  217. if next_element is not None and next_element is not self.previous_element:
  218. next_element.previous_element = self.previous_element
  219. self.previous_element = None
  220. last_child.next_element = None
  221. self.parent = None
  222. if (self.previous_sibling is not None
  223. and self.previous_sibling is not self.next_sibling):
  224. self.previous_sibling.next_sibling = self.next_sibling
  225. if (self.next_sibling is not None
  226. and self.next_sibling is not self.previous_sibling):
  227. self.next_sibling.previous_sibling = self.previous_sibling
  228. self.previous_sibling = self.next_sibling = None
  229. return self
  230. def _last_descendant(self, is_initialized=True, accept_self=True):
  231. "Finds the last element beneath this object to be parsed."
  232. if is_initialized and self.next_sibling:
  233. last_child = self.next_sibling.previous_element
  234. else:
  235. last_child = self
  236. while isinstance(last_child, Tag) and last_child.contents:
  237. last_child = last_child.contents[-1]
  238. if not accept_self and last_child is self:
  239. last_child = None
  240. return last_child
  241. # BS3: Not part of the API!
  242. _lastRecursiveChild = _last_descendant
  243. def insert(self, position, new_child):
  244. if new_child is None:
  245. raise ValueError("Cannot insert None into a tag.")
  246. if new_child is self:
  247. raise ValueError("Cannot insert a tag into itself.")
  248. if (isinstance(new_child, str)
  249. and not isinstance(new_child, NavigableString)):
  250. new_child = NavigableString(new_child)
  251. position = min(position, len(self.contents))
  252. if hasattr(new_child, 'parent') and new_child.parent is not None:
  253. # We're 'inserting' an element that's already one
  254. # of this object's children.
  255. if new_child.parent is self:
  256. current_index = self.index(new_child)
  257. if current_index < position:
  258. # We're moving this element further down the list
  259. # of this object's children. That means that when
  260. # we extract this element, our target index will
  261. # jump down one.
  262. position -= 1
  263. new_child.extract()
  264. new_child.parent = self
  265. previous_child = None
  266. if position == 0:
  267. new_child.previous_sibling = None
  268. new_child.previous_element = self
  269. else:
  270. previous_child = self.contents[position - 1]
  271. new_child.previous_sibling = previous_child
  272. new_child.previous_sibling.next_sibling = new_child
  273. new_child.previous_element = previous_child._last_descendant(False)
  274. if new_child.previous_element is not None:
  275. new_child.previous_element.next_element = new_child
  276. new_childs_last_element = new_child._last_descendant(False)
  277. if position >= len(self.contents):
  278. new_child.next_sibling = None
  279. parent = self
  280. parents_next_sibling = None
  281. while parents_next_sibling is None and parent is not None:
  282. parents_next_sibling = parent.next_sibling
  283. parent = parent.parent
  284. if parents_next_sibling is not None:
  285. # We found the element that comes next in the document.
  286. break
  287. if parents_next_sibling is not None:
  288. new_childs_last_element.next_element = parents_next_sibling
  289. else:
  290. # The last element of this tag is the last element in
  291. # the document.
  292. new_childs_last_element.next_element = None
  293. else:
  294. next_child = self.contents[position]
  295. new_child.next_sibling = next_child
  296. if new_child.next_sibling is not None:
  297. new_child.next_sibling.previous_sibling = new_child
  298. new_childs_last_element.next_element = next_child
  299. if new_childs_last_element.next_element is not None:
  300. new_childs_last_element.next_element.previous_element = new_childs_last_element
  301. self.contents.insert(position, new_child)
  302. def append(self, tag):
  303. """Appends the given tag to the contents of this tag."""
  304. self.insert(len(self.contents), tag)
  305. def insert_before(self, predecessor):
  306. """Makes the given element the immediate predecessor of this one.
  307. The two elements will have the same parent, and the given element
  308. will be immediately before this one.
  309. """
  310. if self is predecessor:
  311. raise ValueError("Can't insert an element before itself.")
  312. parent = self.parent
  313. if parent is None:
  314. raise ValueError(
  315. "Element has no parent, so 'before' has no meaning.")
  316. # Extract first so that the index won't be screwed up if they
  317. # are siblings.
  318. if isinstance(predecessor, PageElement):
  319. predecessor.extract()
  320. index = parent.index(self)
  321. parent.insert(index, predecessor)
  322. def insert_after(self, successor):
  323. """Makes the given element the immediate successor of this one.
  324. The two elements will have the same parent, and the given element
  325. will be immediately after this one.
  326. """
  327. if self is successor:
  328. raise ValueError("Can't insert an element after itself.")
  329. parent = self.parent
  330. if parent is None:
  331. raise ValueError(
  332. "Element has no parent, so 'after' has no meaning.")
  333. # Extract first so that the index won't be screwed up if they
  334. # are siblings.
  335. if isinstance(successor, PageElement):
  336. successor.extract()
  337. index = parent.index(self)
  338. parent.insert(index+1, successor)
  339. def find_next(self, name=None, attrs={}, text=None, **kwargs):
  340. """Returns the first item that matches the given criteria and
  341. appears after this Tag in the document."""
  342. return self._find_one(self.find_all_next, name, attrs, text, **kwargs)
  343. findNext = find_next # BS3
  344. def find_all_next(self, name=None, attrs={}, text=None, limit=None,
  345. **kwargs):
  346. """Returns all items that match the given criteria and appear
  347. after this Tag in the document."""
  348. return self._find_all(name, attrs, text, limit, self.next_elements,
  349. **kwargs)
  350. findAllNext = find_all_next # BS3
  351. def find_next_sibling(self, name=None, attrs={}, text=None, **kwargs):
  352. """Returns the closest sibling to this Tag that matches the
  353. given criteria and appears after this Tag in the document."""
  354. return self._find_one(self.find_next_siblings, name, attrs, text,
  355. **kwargs)
  356. findNextSibling = find_next_sibling # BS3
  357. def find_next_siblings(self, name=None, attrs={}, text=None, limit=None,
  358. **kwargs):
  359. """Returns the siblings of this Tag that match the given
  360. criteria and appear after this Tag in the document."""
  361. return self._find_all(name, attrs, text, limit,
  362. self.next_siblings, **kwargs)
  363. findNextSiblings = find_next_siblings # BS3
  364. fetchNextSiblings = find_next_siblings # BS2
  365. def find_previous(self, name=None, attrs={}, text=None, **kwargs):
  366. """Returns the first item that matches the given criteria and
  367. appears before this Tag in the document."""
  368. return self._find_one(
  369. self.find_all_previous, name, attrs, text, **kwargs)
  370. findPrevious = find_previous # BS3
  371. def find_all_previous(self, name=None, attrs={}, text=None, limit=None,
  372. **kwargs):
  373. """Returns all items that match the given criteria and appear
  374. before this Tag in the document."""
  375. return self._find_all(name, attrs, text, limit, self.previous_elements,
  376. **kwargs)
  377. findAllPrevious = find_all_previous # BS3
  378. fetchPrevious = find_all_previous # BS2
  379. def find_previous_sibling(self, name=None, attrs={}, text=None, **kwargs):
  380. """Returns the closest sibling to this Tag that matches the
  381. given criteria and appears before this Tag in the document."""
  382. return self._find_one(self.find_previous_siblings, name, attrs, text,
  383. **kwargs)
  384. findPreviousSibling = find_previous_sibling # BS3
  385. def find_previous_siblings(self, name=None, attrs={}, text=None,
  386. limit=None, **kwargs):
  387. """Returns the siblings of this Tag that match the given
  388. criteria and appear before this Tag in the document."""
  389. return self._find_all(name, attrs, text, limit,
  390. self.previous_siblings, **kwargs)
  391. findPreviousSiblings = find_previous_siblings # BS3
  392. fetchPreviousSiblings = find_previous_siblings # BS2
  393. def find_parent(self, name=None, attrs={}, **kwargs):
  394. """Returns the closest parent of this Tag that matches the given
  395. criteria."""
  396. # NOTE: We can't use _find_one because findParents takes a different
  397. # set of arguments.
  398. r = None
  399. l = self.find_parents(name, attrs, 1, **kwargs)
  400. if l:
  401. r = l[0]
  402. return r
  403. findParent = find_parent # BS3
  404. def find_parents(self, name=None, attrs={}, limit=None, **kwargs):
  405. """Returns the parents of this Tag that match the given
  406. criteria."""
  407. return self._find_all(name, attrs, None, limit, self.parents,
  408. **kwargs)
  409. findParents = find_parents # BS3
  410. fetchParents = find_parents # BS2
  411. @property
  412. def next(self):
  413. return self.next_element
  414. @property
  415. def previous(self):
  416. return self.previous_element
  417. #These methods do the real heavy lifting.
  418. def _find_one(self, method, name, attrs, text, **kwargs):
  419. r = None
  420. l = method(name, attrs, text, 1, **kwargs)
  421. if l:
  422. r = l[0]
  423. return r
  424. def _find_all(self, name, attrs, text, limit, generator, **kwargs):
  425. "Iterates over a generator looking for things that match."
  426. if text is None and 'string' in kwargs:
  427. text = kwargs['string']
  428. del kwargs['string']
  429. if isinstance(name, SoupStrainer):
  430. strainer = name
  431. else:
  432. strainer = SoupStrainer(name, attrs, text, **kwargs)
  433. if text is None and not limit and not attrs and not kwargs:
  434. if name is True or name is None:
  435. # Optimization to find all tags.
  436. result = (element for element in generator
  437. if isinstance(element, Tag))
  438. return ResultSet(strainer, result)
  439. elif isinstance(name, str):
  440. # Optimization to find all tags with a given name.
  441. result = (element for element in generator
  442. if isinstance(element, Tag)
  443. and element.name == name)
  444. return ResultSet(strainer, result)
  445. results = ResultSet(strainer)
  446. while True:
  447. try:
  448. i = next(generator)
  449. except StopIteration:
  450. break
  451. if i:
  452. found = strainer.search(i)
  453. if found:
  454. results.append(found)
  455. if limit and len(results) >= limit:
  456. break
  457. return results
  458. #These generators can be used to navigate starting from both
  459. #NavigableStrings and Tags.
  460. @property
  461. def next_elements(self):
  462. i = self.next_element
  463. while i is not None:
  464. yield i
  465. i = i.next_element
  466. @property
  467. def next_siblings(self):
  468. i = self.next_sibling
  469. while i is not None:
  470. yield i
  471. i = i.next_sibling
  472. @property
  473. def previous_elements(self):
  474. i = self.previous_element
  475. while i is not None:
  476. yield i
  477. i = i.previous_element
  478. @property
  479. def previous_siblings(self):
  480. i = self.previous_sibling
  481. while i is not None:
  482. yield i
  483. i = i.previous_sibling
  484. @property
  485. def parents(self):
  486. i = self.parent
  487. while i is not None:
  488. yield i
  489. i = i.parent
  490. # Methods for supporting CSS selectors.
  491. tag_name_re = re.compile('^[a-zA-Z0-9][-.a-zA-Z0-9:_]*$')
  492. # /^([a-zA-Z0-9][-.a-zA-Z0-9:_]*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  493. # \---------------------------/ \---/\-------------/ \-------/
  494. # | | | |
  495. # | | | The value
  496. # | | ~,|,^,$,* or =
  497. # | Attribute
  498. # Tag
  499. attribselect_re = re.compile(
  500. r'^(?P<tag>[a-zA-Z0-9][-.a-zA-Z0-9:_]*)?\[(?P<attribute>[\w-]+)(?P<operator>[=~\|\^\$\*]?)' +
  501. r'=?"?(?P<value>[^\]"]*)"?\]$'
  502. )
  503. def _attr_value_as_string(self, value, default=None):
  504. """Force an attribute value into a string representation.
  505. A multi-valued attribute will be converted into a
  506. space-separated stirng.
  507. """
  508. value = self.get(value, default)
  509. if isinstance(value, list) or isinstance(value, tuple):
  510. value =" ".join(value)
  511. return value
  512. def _tag_name_matches_and(self, function, tag_name):
  513. if not tag_name:
  514. return function
  515. else:
  516. def _match(tag):
  517. return tag.name == tag_name and function(tag)
  518. return _match
  519. def _attribute_checker(self, operator, attribute, value=''):
  520. """Create a function that performs a CSS selector operation.
  521. Takes an operator, attribute and optional value. Returns a
  522. function that will return True for elements that match that
  523. combination.
  524. """
  525. if operator == '=':
  526. # string representation of `attribute` is equal to `value`
  527. return lambda el: el._attr_value_as_string(attribute) == value
  528. elif operator == '~':
  529. # space-separated list representation of `attribute`
  530. # contains `value`
  531. def _includes_value(element):
  532. attribute_value = element.get(attribute, [])
  533. if not isinstance(attribute_value, list):
  534. attribute_value = attribute_value.split()
  535. return value in attribute_value
  536. return _includes_value
  537. elif operator == '^':
  538. # string representation of `attribute` starts with `value`
  539. return lambda el: el._attr_value_as_string(
  540. attribute, '').startswith(value)
  541. elif operator == '$':
  542. # string represenation of `attribute` ends with `value`
  543. return lambda el: el._attr_value_as_string(
  544. attribute, '').endswith(value)
  545. elif operator == '*':
  546. # string representation of `attribute` contains `value`
  547. return lambda el: value in el._attr_value_as_string(attribute, '')
  548. elif operator == '|':
  549. # string representation of `attribute` is either exactly
  550. # `value` or starts with `value` and then a dash.
  551. def _is_or_starts_with_dash(element):
  552. attribute_value = element._attr_value_as_string(attribute, '')
  553. return (attribute_value == value or attribute_value.startswith(
  554. value + '-'))
  555. return _is_or_starts_with_dash
  556. else:
  557. return lambda el: el.has_attr(attribute)
  558. # Old non-property versions of the generators, for backwards
  559. # compatibility with BS3.
  560. def nextGenerator(self):
  561. return self.next_elements
  562. def nextSiblingGenerator(self):
  563. return self.next_siblings
  564. def previousGenerator(self):
  565. return self.previous_elements
  566. def previousSiblingGenerator(self):
  567. return self.previous_siblings
  568. def parentGenerator(self):
  569. return self.parents
  570. class NavigableString(str, PageElement):
  571. PREFIX = ''
  572. SUFFIX = ''
  573. def __new__(cls, value):
  574. """Create a new NavigableString.
  575. When unpickling a NavigableString, this method is called with
  576. the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
  577. passed in to the superclass's __new__ or the superclass won't know
  578. how to handle non-ASCII characters.
  579. """
  580. if isinstance(value, str):
  581. u = str.__new__(cls, value)
  582. else:
  583. u = str.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
  584. u.setup()
  585. return u
  586. def __copy__(self):
  587. """A copy of a NavigableString has the same contents and class
  588. as the original, but it is not connected to the parse tree.
  589. """
  590. return type(self)(self)
  591. def __getnewargs__(self):
  592. return (str(self),)
  593. def __getattr__(self, attr):
  594. """text.string gives you text. This is for backwards
  595. compatibility for Navigable*String, but for CData* it lets you
  596. get the string without the CData wrapper."""
  597. if attr == 'string':
  598. return self
  599. else:
  600. raise AttributeError(
  601. "'%s' object has no attribute '%s'" % (
  602. self.__class__.__name__, attr))
  603. def output_ready(self, formatter="minimal"):
  604. output = self.format_string(self, formatter)
  605. return self.PREFIX + output + self.SUFFIX
  606. @property
  607. def name(self):
  608. return None
  609. @name.setter
  610. def name(self, name):
  611. raise AttributeError("A NavigableString cannot be given a name.")
  612. class PreformattedString(NavigableString):
  613. """A NavigableString not subject to the normal formatting rules.
  614. The string will be passed into the formatter (to trigger side effects),
  615. but the return value will be ignored.
  616. """
  617. def output_ready(self, formatter="minimal"):
  618. """CData strings are passed into the formatter.
  619. But the return value is ignored."""
  620. self.format_string(self, formatter)
  621. return self.PREFIX + self + self.SUFFIX
  622. class CData(PreformattedString):
  623. PREFIX = '<![CDATA['
  624. SUFFIX = ']]>'
  625. class ProcessingInstruction(PreformattedString):
  626. PREFIX = '<?'
  627. SUFFIX = '>'
  628. class Comment(PreformattedString):
  629. PREFIX = '<!--'
  630. SUFFIX = '-->'
  631. class Declaration(PreformattedString):
  632. PREFIX = '<?'
  633. SUFFIX = '?>'
  634. class Doctype(PreformattedString):
  635. @classmethod
  636. def for_name_and_ids(cls, name, pub_id, system_id):
  637. value = name or ''
  638. if pub_id is not None:
  639. value += ' PUBLIC "%s"' % pub_id
  640. if system_id is not None:
  641. value += ' "%s"' % system_id
  642. elif system_id is not None:
  643. value += ' SYSTEM "%s"' % system_id
  644. return Doctype(value)
  645. PREFIX = '<!DOCTYPE '
  646. SUFFIX = '>\n'
  647. class Tag(PageElement):
  648. """Represents a found HTML tag with its attributes and contents."""
  649. def __init__(self, parser=None, builder=None, name=None, namespace=None,
  650. prefix=None, attrs=None, parent=None, previous=None):
  651. "Basic constructor."
  652. if parser is None:
  653. self.parser_class = None
  654. else:
  655. # We don't actually store the parser object: that lets extracted
  656. # chunks be garbage-collected.
  657. self.parser_class = parser.__class__
  658. if name is None:
  659. raise ValueError("No value provided for new tag's name.")
  660. self.name = name
  661. self.namespace = namespace
  662. self.prefix = prefix
  663. if attrs is None:
  664. attrs = {}
  665. elif attrs:
  666. if builder is not None and builder.cdata_list_attributes:
  667. attrs = builder._replace_cdata_list_attribute_values(
  668. self.name, attrs)
  669. else:
  670. attrs = dict(attrs)
  671. else:
  672. attrs = dict(attrs)
  673. self.attrs = attrs
  674. self.contents = []
  675. self.setup(parent, previous)
  676. self.hidden = False
  677. # Set up any substitutions, such as the charset in a META tag.
  678. if builder is not None:
  679. builder.set_up_substitutions(self)
  680. self.can_be_empty_element = builder.can_be_empty_element(name)
  681. else:
  682. self.can_be_empty_element = False
  683. parserClass = _alias("parser_class") # BS3
  684. def __copy__(self):
  685. """A copy of a Tag is a new Tag, unconnected to the parse tree.
  686. Its contents are a copy of the old Tag's contents.
  687. """
  688. clone = type(self)(None, self.builder, self.name, self.namespace,
  689. self.nsprefix, self.attrs)
  690. for attr in ('can_be_empty_element', 'hidden'):
  691. setattr(clone, attr, getattr(self, attr))
  692. for child in self.contents:
  693. clone.append(child.__copy__())
  694. return clone
  695. @property
  696. def is_empty_element(self):
  697. """Is this tag an empty-element tag? (aka a self-closing tag)
  698. A tag that has contents is never an empty-element tag.
  699. A tag that has no contents may or may not be an empty-element
  700. tag. It depends on the builder used to create the tag. If the
  701. builder has a designated list of empty-element tags, then only
  702. a tag whose name shows up in that list is considered an
  703. empty-element tag.
  704. If the builder has no designated list of empty-element tags,
  705. then any tag with no contents is an empty-element tag.
  706. """
  707. return len(self.contents) == 0 and self.can_be_empty_element
  708. isSelfClosing = is_empty_element # BS3
  709. @property
  710. def string(self):
  711. """Convenience property to get the single string within this tag.
  712. :Return: If this tag has a single string child, return value
  713. is that string. If this tag has no children, or more than one
  714. child, return value is None. If this tag has one child tag,
  715. return value is the 'string' attribute of the child tag,
  716. recursively.
  717. """
  718. if len(self.contents) != 1:
  719. return None
  720. child = self.contents[0]
  721. if isinstance(child, NavigableString):
  722. return child
  723. return child.string
  724. @string.setter
  725. def string(self, string):
  726. self.clear()
  727. self.append(string.__class__(string))
  728. def _all_strings(self, strip=False, types=(NavigableString, CData)):
  729. """Yield all strings of certain classes, possibly stripping them.
  730. By default, yields only NavigableString and CData objects. So
  731. no comments, processing instructions, etc.
  732. """
  733. for descendant in self.descendants:
  734. if (
  735. (types is None and not isinstance(descendant, NavigableString))
  736. or
  737. (types is not None and type(descendant) not in types)):
  738. continue
  739. if strip:
  740. descendant = descendant.strip()
  741. if len(descendant) == 0:
  742. continue
  743. yield descendant
  744. strings = property(_all_strings)
  745. @property
  746. def stripped_strings(self):
  747. for string in self._all_strings(True):
  748. yield string
  749. def get_text(self, separator="", strip=False,
  750. types=(NavigableString, CData)):
  751. """
  752. Get all child strings, concatenated using the given separator.
  753. """
  754. return separator.join([s for s in self._all_strings(
  755. strip, types=types)])
  756. getText = get_text
  757. text = property(get_text)
  758. def decompose(self):
  759. """Recursively destroys the contents of this tree."""
  760. self.extract()
  761. i = self
  762. while i is not None:
  763. next = i.next_element
  764. i.__dict__.clear()
  765. i.contents = []
  766. i = next
  767. def clear(self, decompose=False):
  768. """
  769. Extract all children. If decompose is True, decompose instead.
  770. """
  771. if decompose:
  772. for element in self.contents[:]:
  773. if isinstance(element, Tag):
  774. element.decompose()
  775. else:
  776. element.extract()
  777. else:
  778. for element in self.contents[:]:
  779. element.extract()
  780. def index(self, element):
  781. """
  782. Find the index of a child by identity, not value. Avoids issues with
  783. tag.contents.index(element) getting the index of equal elements.
  784. """
  785. for i, child in enumerate(self.contents):
  786. if child is element:
  787. return i
  788. raise ValueError("Tag.index: element not in tag")
  789. def get(self, key, default=None):
  790. """Returns the value of the 'key' attribute for the tag, or
  791. the value given for 'default' if it doesn't have that
  792. attribute."""
  793. return self.attrs.get(key, default)
  794. def has_attr(self, key):
  795. return key in self.attrs
  796. def __hash__(self):
  797. return str(self).__hash__()
  798. def __getitem__(self, key):
  799. """tag[key] returns the value of the 'key' attribute for the tag,
  800. and throws an exception if it's not there."""
  801. return self.attrs[key]
  802. def __iter__(self):
  803. "Iterating over a tag iterates over its contents."
  804. return iter(self.contents)
  805. def __len__(self):
  806. "The length of a tag is the length of its list of contents."
  807. return len(self.contents)
  808. def __contains__(self, x):
  809. return x in self.contents
  810. def __bool__(self):
  811. "A tag is non-None even if it has no contents."
  812. return True
  813. def __setitem__(self, key, value):
  814. """Setting tag[key] sets the value of the 'key' attribute for the
  815. tag."""
  816. self.attrs[key] = value
  817. def __delitem__(self, key):
  818. "Deleting tag[key] deletes all 'key' attributes for the tag."
  819. self.attrs.pop(key, None)
  820. def __call__(self, *args, **kwargs):
  821. """Calling a tag like a function is the same as calling its
  822. find_all() method. Eg. tag('a') returns a list of all the A tags
  823. found within this tag."""
  824. return self.find_all(*args, **kwargs)
  825. def __getattr__(self, tag):
  826. #print "Getattr %s.%s" % (self.__class__, tag)
  827. if len(tag) > 3 and tag.endswith('Tag'):
  828. # BS3: soup.aTag -> "soup.find("a")
  829. tag_name = tag[:-3]
  830. warnings.warn(
  831. '.%sTag is deprecated, use .find("%s") instead.' % (
  832. tag_name, tag_name))
  833. return self.find(tag_name)
  834. # We special case contents to avoid recursion.
  835. elif not tag.startswith("__") and not tag=="contents":
  836. return self.find(tag)
  837. raise AttributeError(
  838. "'%s' object has no attribute '%s'" % (self.__class__, tag))
  839. def __eq__(self, other):
  840. """Returns true iff this tag has the same name, the same attributes,
  841. and the same contents (recursively) as the given tag."""
  842. if self is other:
  843. return True
  844. if (not hasattr(other, 'name') or
  845. not hasattr(other, 'attrs') or
  846. not hasattr(other, 'contents') or
  847. self.name != other.name or
  848. self.attrs != other.attrs or
  849. len(self) != len(other)):
  850. return False
  851. for i, my_child in enumerate(self.contents):
  852. if my_child != other.contents[i]:
  853. return False
  854. return True
  855. def __ne__(self, other):
  856. """Returns true iff this tag is not identical to the other tag,
  857. as defined in __eq__."""
  858. return not self == other
  859. def __repr__(self, encoding="unicode-escape"):
  860. """Renders this tag as a string."""
  861. if PY3K:
  862. # "The return value must be a string object", i.e. Unicode
  863. return self.decode()
  864. else:
  865. # "The return value must be a string object", i.e. a bytestring.
  866. # By convention, the return value of __repr__ should also be
  867. # an ASCII string.
  868. return self.encode(encoding)
  869. def __unicode__(self):
  870. return self.decode()
  871. def __str__(self):
  872. if PY3K:
  873. return self.decode()
  874. else:
  875. return self.encode()
  876. if PY3K:
  877. __str__ = __repr__ = __unicode__
  878. def encode(self, encoding=DEFAULT_OUTPUT_ENCODING,
  879. indent_level=None, formatter="minimal",
  880. errors="xmlcharrefreplace"):
  881. # Turn the data structure into Unicode, then encode the
  882. # Unicode.
  883. u = self.decode(indent_level, encoding, formatter)
  884. return u.encode(encoding, errors)
  885. def _should_pretty_print(self, indent_level):
  886. """Should this tag be pretty-printed?"""
  887. return (
  888. indent_level is not None and
  889. (self.name not in HTMLAwareEntitySubstitution.preformatted_tags
  890. or self._is_xml))
  891. def decode(self, indent_level=None,
  892. eventual_encoding=DEFAULT_OUTPUT_ENCODING,
  893. formatter="minimal"):
  894. """Returns a Unicode representation of this tag and its contents.
  895. :param eventual_encoding: The tag is destined to be
  896. encoded into this encoding. This method is _not_
  897. responsible for performing that encoding. This information
  898. is passed in so that it can be substituted in if the
  899. document contains a <META> tag that mentions the document's
  900. encoding.
  901. """
  902. # First off, turn a string formatter into a function. This
  903. # will stop the lookup from happening over and over again.
  904. if not isinstance(formatter, collections.Callable):
  905. formatter = self._formatter_for_name(formatter)
  906. attrs = []
  907. if self.attrs:
  908. for key, val in sorted(self.attrs.items()):
  909. if val is None:
  910. decoded = key
  911. else:
  912. if isinstance(val, list) or isinstance(val, tuple):
  913. val = ' '.join(val)
  914. elif not isinstance(val, str):
  915. val = str(val)
  916. elif (
  917. isinstance(val, AttributeValueWithCharsetSubstitution)
  918. and eventual_encoding is not None):
  919. val = val.encode(eventual_encoding)
  920. text = self.format_string(val, formatter)
  921. decoded = (
  922. str(key) + '='
  923. + EntitySubstitution.quoted_attribute_value(text))
  924. attrs.append(decoded)
  925. close = ''
  926. closeTag = ''
  927. prefix = ''
  928. if self.prefix:
  929. prefix = self.prefix + ":"
  930. if self.is_empty_element:
  931. close = '/'
  932. else:
  933. closeTag = '</%s%s>' % (prefix, self.name)
  934. pretty_print = self._should_pretty_print(indent_level)
  935. space = ''
  936. indent_space = ''
  937. if indent_level is not None:
  938. indent_space = (' ' * (indent_level - 1))
  939. if pretty_print:
  940. space = indent_space
  941. indent_contents = indent_level + 1
  942. else:
  943. indent_contents = None
  944. contents = self.decode_contents(
  945. indent_contents, eventual_encoding, formatter)
  946. if self.hidden:
  947. # This is the 'document root' object.
  948. s = contents
  949. else:
  950. s = []
  951. attribute_string = ''
  952. if attrs:
  953. attribute_string = ' ' + ' '.join(attrs)
  954. if indent_level is not None:
  955. # Even if this particular tag is not pretty-printed,
  956. # we should indent up to the start of the tag.
  957. s.append(indent_space)
  958. s.append('<%s%s%s%s>' % (
  959. prefix, self.name, attribute_string, close))
  960. if pretty_print:
  961. s.append("\n")
  962. s.append(contents)
  963. if pretty_print and contents and contents[-1] != "\n":
  964. s.append("\n")
  965. if pretty_print and closeTag:
  966. s.append(space)
  967. s.append(closeTag)
  968. if indent_level is not None and closeTag and self.next_sibling:
  969. # Even if this particular tag is not pretty-printed,
  970. # we're now done with the tag, and we should add a
  971. # newline if appropriate.
  972. s.append("\n")
  973. s = ''.join(s)
  974. return s
  975. def prettify(self, encoding=None, formatter="minimal"):
  976. if encoding is None:
  977. return self.decode(True, formatter=formatter)
  978. else:
  979. return self.encode(encoding, True, formatter=formatter)
  980. def decode_contents(self, indent_level=None,
  981. eventual_encoding=DEFAULT_OUTPUT_ENCODING,
  982. formatter="minimal"):
  983. """Renders the contents of this tag as a Unicode string.
  984. :param indent_level: Each line of the rendering will be
  985. indented this many spaces.
  986. :param eventual_encoding: The tag is destined to be
  987. encoded into this encoding. This method is _not_
  988. responsible for performing that encoding. This information
  989. is passed in so that it can be substituted in if the
  990. document contains a <META> tag that mentions the document's
  991. encoding.
  992. :param formatter: The output formatter responsible for converting
  993. entities to Unicode characters.
  994. """
  995. # First off, turn a string formatter into a function. This
  996. # will stop the lookup from happening over and over again.
  997. if not isinstance(formatter, collections.Callable):
  998. formatter = self._formatter_for_name(formatter)
  999. pretty_print = (indent_level is not None)
  1000. s = []
  1001. for c in self:
  1002. text = None
  1003. if isinstance(c, NavigableString):
  1004. text = c.output_ready(formatter)
  1005. elif isinstance(c, Tag):
  1006. s.append(c.decode(indent_level, eventual_encoding,
  1007. formatter))
  1008. if text and indent_level and not self.name == 'pre':
  1009. text = text.strip()
  1010. if text:
  1011. if pretty_print and not self.name == 'pre':
  1012. s.append(" " * (indent_level - 1))
  1013. s.append(text)
  1014. if pretty_print and not self.name == 'pre':
  1015. s.append("\n")
  1016. return ''.join(s)
  1017. def encode_contents(
  1018. self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING,
  1019. formatter="minimal"):
  1020. """Renders the contents of this tag as a bytestring.
  1021. :param indent_level: Each line of the rendering will be
  1022. indented this many spaces.
  1023. :param eventual_encoding: The bytestring will be in this encoding.
  1024. :param formatter: The output formatter responsible for converting
  1025. entities to Unicode characters.
  1026. """
  1027. contents = self.decode_contents(indent_level, encoding, formatter)
  1028. return contents.encode(encoding)
  1029. # Old method for BS3 compatibility
  1030. def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
  1031. prettyPrint=False, indentLevel=0):
  1032. if not prettyPrint:
  1033. indentLevel = None
  1034. return self.encode_contents(
  1035. indent_level=indentLevel, encoding=encoding)
  1036. #Soup methods
  1037. def find(self, name=None, attrs={}, recursive=True, text=None,
  1038. **kwargs):
  1039. """Return only the first child of this Tag matching the given
  1040. criteria."""
  1041. r = None
  1042. l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
  1043. if l:
  1044. r = l[0]
  1045. return r
  1046. findChild = find
  1047. def find_all(self, name=None, attrs={}, recursive=True, text=None,
  1048. limit=None, **kwargs):
  1049. """Extracts a list of Tag objects that match the given
  1050. criteria. You can specify the name of the Tag and any
  1051. attributes you want the Tag to have.
  1052. The value of a key-value pair in the 'attrs' map can be a
  1053. string, a list of strings, a regular expression object, or a
  1054. callable that takes a string and returns whether or not the
  1055. string matches for some custom definition of 'matches'. The
  1056. same is true of the tag name."""
  1057. generator = self.descendants
  1058. if not recursive:
  1059. generator = self.children
  1060. return self._find_all(name, attrs, text, limit, generator, **kwargs)
  1061. findAll = find_all # BS3
  1062. findChildren = find_all # BS2
  1063. #Generator methods
  1064. @property
  1065. def children(self):
  1066. # return iter() to make the purpose of the method clear
  1067. return iter(self.contents) # XXX This seems to be untested.
  1068. @property
  1069. def descendants(self):
  1070. if not len(self.contents):
  1071. return
  1072. stopNode = self._last_descendant().next_element
  1073. current = self.contents[0]
  1074. while current is not stopNode:
  1075. yield current
  1076. current = current.next_element
  1077. # CSS selector code
  1078. _selector_combinators = ['>', '+', '~']
  1079. _select_debug = False
  1080. def select_one(self, selector):
  1081. """Perform a CSS selection operation on the current element."""
  1082. value = self.select(selector, limit=1)
  1083. if value:
  1084. return value[0]
  1085. return None
  1086. def select(self, selector, _candidate_generator=None, limit=None):
  1087. """Perform a CSS selection operation on the current element."""
  1088. # Handle grouping selectors if ',' exists, ie: p,a
  1089. if ',' in selector:
  1090. context = []
  1091. for partial_selector in selector.split(','):
  1092. partial_selector = partial_selector.strip()
  1093. if partial_selector == '':
  1094. raise ValueError('Invalid group selection syntax: %s' % selector)
  1095. candidates = self.select(partial_selector, limit=limit)
  1096. for candidate in candidates:
  1097. if candidate not in context:
  1098. context.append(candidate)
  1099. if limit and len(context) >= limit:
  1100. break
  1101. return context
  1102. tokens = selector.split()
  1103. current_context = [self]
  1104. if tokens[-1] in self._selector_combinators:
  1105. raise ValueError(
  1106. 'Final combinator "%s" is missing an argument.' % tokens[-1])
  1107. if self._select_debug:
  1108. print('Running CSS selector "%s"' % selector)
  1109. for index, token in enumerate(tokens):
  1110. new_context = []
  1111. new_context_ids = set([])
  1112. if tokens[index-1] in self._selector_combinators:
  1113. # This token was consumed by the previous combinator. Skip it.
  1114. if self._select_debug:
  1115. print(' Token was consumed by the previous combinator.')
  1116. continue
  1117. if self._select_debug:
  1118. print(' Considering token "%s"' % token)
  1119. recursive_candidate_generator = None
  1120. tag_name = None
  1121. # Each operation corresponds to a checker function, a rule
  1122. # for determining whether a candidate matches the
  1123. # selector. Candidates are generated by the active
  1124. # iterator.
  1125. checker = None
  1126. m = self.attribselect_re.match(token)
  1127. if m is not None:
  1128. # Attribute selector
  1129. tag_name, attribute, operator, value = m.groups()
  1130. checker = self._attribute_checker(operator, attribute, value)
  1131. elif '#' in token:
  1132. # ID selector
  1133. tag_name, tag_id = token.split('#', 1)
  1134. def id_matches(tag):
  1135. return tag.get('id', None) == tag_id
  1136. checker = id_matches
  1137. elif '.' in token:
  1138. # Class selector
  1139. tag_name, klass = token.split('.', 1)
  1140. classes = set(klass.split('.'))
  1141. def classes_match(candidate):
  1142. return classes.issubset(candidate.get('class', []))
  1143. checker = classes_match
  1144. elif ':' in token:
  1145. # Pseudo-class
  1146. tag_name, pseudo = token.split(':', 1)
  1147. if tag_name == '':
  1148. raise ValueError(
  1149. "A pseudo-class must be prefixed with a tag name.")
  1150. pseudo_attributes = re.match('([a-zA-Z\d-]+)\(([a-zA-Z\d]+)\)', pseudo)
  1151. found = []
  1152. if pseudo_attributes is None:
  1153. pseudo_type = pseudo
  1154. pseudo_value = None
  1155. else:
  1156. pseudo_type, pseudo_value = pseudo_attributes.groups()
  1157. if pseudo_type == 'nth-of-type':
  1158. try:
  1159. pseudo_value = int(pseudo_value)
  1160. except:
  1161. raise NotImplementedError(
  1162. 'Only numeric values are currently supported for the nth-of-type pseudo-class.')
  1163. if pseudo_value < 1:
  1164. raise ValueError(
  1165. 'nth-of-type pseudo-class value must be at least 1.')
  1166. class Counter(object):
  1167. def __init__(self, destination):
  1168. self.count = 0
  1169. self.destination = destination
  1170. def nth_child_of_type(self, tag):
  1171. self.count += 1
  1172. if self.count == self.destination:
  1173. return True
  1174. if self.count > self.destination:
  1175. # Stop the generator that's sending us
  1176. # these things.
  1177. raise StopIteration()
  1178. return False
  1179. checker = Counter(pseudo_value).nth_child_of_type
  1180. else:
  1181. raise NotImplementedError(
  1182. 'Only the following pseudo-classes are implemented: nth-of-type.')
  1183. elif token == '*':
  1184. # Star selector -- matches everything
  1185. pass
  1186. elif token == '>':
  1187. # Run the next token as a CSS selector against the
  1188. # direct children of each tag in the current context.
  1189. recursive_candidate_generator = lambda tag: tag.children
  1190. elif token == '~':
  1191. # Run the next token as a CSS selector against the
  1192. # siblings of each tag in the current context.
  1193. recursive_candidate_generator = lambda tag: tag.next_siblings
  1194. elif token == '+':
  1195. # For each tag in the current context, run the next
  1196. # token as a CSS selector against the tag's next
  1197. # sibling that's a tag.
  1198. def next_tag_sibling(tag):
  1199. yield tag.find_next_sibling(True)
  1200. recursive_candidate_generator = next_tag_sibling
  1201. elif self.tag_name_re.match(token):
  1202. # Just a tag name.
  1203. tag_name = token
  1204. else:
  1205. raise ValueError(
  1206. 'Unsupported or invalid CSS selector: "%s"' % token)
  1207. if recursive_candidate_generator:
  1208. # This happens when the selector looks like "> foo".
  1209. #
  1210. # The generator calls select() recursively on every
  1211. # member of the current context, passing in a different
  1212. # candidate generator and a different selector.
  1213. #
  1214. # In the case of "> foo", the candidate generator is
  1215. # one that yields a tag's direct children (">"), and
  1216. # the selector is "foo".
  1217. next_token = tokens[index+1]
  1218. def recursive_select(tag):
  1219. if self._select_debug:
  1220. print(' Calling select("%s") recursively on %s %s' % (next_token, tag.name, tag.attrs))
  1221. print('-' * 40)
  1222. for i in tag.select(next_token, recursive_candidate_generator):
  1223. if self._select_debug:
  1224. print('(Recursive select picked up candidate %s %s)' % (i.name, i.attrs))
  1225. yield i
  1226. if self._select_debug:
  1227. print('-' * 40)
  1228. _use_candidate_generator = recursive_select
  1229. elif _candidate_generator is None:
  1230. # By default, a tag's candidates are all of its
  1231. # children. If tag_name is defined, only yield tags
  1232. # with that name.
  1233. if self._select_debug:
  1234. if tag_name:
  1235. check = "[any]"
  1236. else:
  1237. check = tag_name
  1238. print(' Default candidate generator, tag name="%s"' % check)
  1239. if self._select_debug:
  1240. # This is redundant with later code, but it stops
  1241. # a bunch of bogus tags from cluttering up the
  1242. # debug log.
  1243. def default_candidate_generator(tag):
  1244. for child in tag.descendants:
  1245. if not isinstance(child, Tag):
  1246. continue
  1247. if tag_name and not child.name == tag_name:
  1248. continue
  1249. yield child
  1250. _use_candidate_generator = default_candidate_generator
  1251. else:
  1252. _use_candidate_generator = lambda tag: tag.descendants
  1253. else:
  1254. _use_candidate_generator = _candidate_generator
  1255. count = 0
  1256. for tag in current_context:
  1257. if self._select_debug:
  1258. print(" Running candidate generator on %s %s" % (
  1259. tag.name, repr(tag.attrs)))
  1260. for candidate in _use_candidate_generator(tag):
  1261. if not isinstance(candidate, Tag):
  1262. continue
  1263. if tag_name and candidate.name != tag_name:
  1264. continue
  1265. if checker is not None:
  1266. try:
  1267. result = checker(candidate)
  1268. except StopIteration:
  1269. # The checker has decided we should no longer
  1270. # run the generator.
  1271. break
  1272. if checker is None or result:
  1273. if self._select_debug:
  1274. print(" SUCCESS %s %s" % (candidate.name, repr(candidate.attrs)))
  1275. if id(candidate) not in new_context_ids:
  1276. # If a tag matches a selector more than once,
  1277. # don't include it in the context more than once.
  1278. new_context.append(candidate)
  1279. new_context_ids.add(id(candidate))
  1280. if limit and len(new_context) >= limit:
  1281. break
  1282. elif self._select_debug:
  1283. print(" FAILURE %s %s" % (candidate.name, repr(candidate.attrs)))
  1284. current_context = new_context
  1285. if self._select_debug:
  1286. print("Final verdict:")
  1287. for i in current_context:
  1288. print(" %s %s" % (i.name, i.attrs))
  1289. return current_context
  1290. # Old names for backwards compatibility
  1291. def childGenerator(self):
  1292. return self.children
  1293. def recursiveChildGenerator(self):
  1294. return self.descendants
  1295. def has_key(self, key):
  1296. """This was kind of misleading because has_key() (attributes)
  1297. was different from __in__ (contents). has_key() is gone in
  1298. Python 3, anyway."""
  1299. warnings.warn('has_key is deprecated. Use has_attr("%s") instead.' % (
  1300. key))
  1301. return self.has_attr(key)
  1302. # Next, a couple classes to represent queries and their results.
  1303. class SoupStrainer(object):
  1304. """Encapsulates a number of ways of matching a markup element (tag or
  1305. text)."""
  1306. def __init__(self, name=None, attrs={}, text=None, **kwargs):
  1307. self.name = self._normalize_search_value(name)
  1308. if not isinstance(attrs, dict):
  1309. # Treat a non-dict value for attrs as a search for the 'class'
  1310. # attribute.
  1311. kwargs['class'] = attrs
  1312. attrs = None
  1313. if 'class_' in kwargs:
  1314. # Treat class_="foo" as a search for the 'class'
  1315. # attribute, overriding any non-dict value for attrs.
  1316. kwargs['class'] = kwargs['class_']
  1317. del kwargs['class_']
  1318. if kwargs:
  1319. if attrs:
  1320. attrs = attrs.copy()
  1321. attrs.update(kwargs)
  1322. else:
  1323. attrs = kwargs
  1324. normalized_attrs = {}
  1325. for key, value in list(attrs.items()):
  1326. normalized_attrs[key] = self._normalize_search_value(value)
  1327. self.attrs = normalized_attrs
  1328. self.text = self._normalize_search_value(text)
  1329. def _normalize_search_value(self, value):
  1330. # Leave it alone if it's a Unicode string, a callable, a
  1331. # regular expression, a boolean, or None.
  1332. if (isinstance(value, str) or isinstance(value, collections.Callable) or hasattr(value, 'match')
  1333. or isinstance(value, bool) or value is None):
  1334. return value
  1335. # If it's a bytestring, convert it to Unicode, treating it as UTF-8.
  1336. if isinstance(value, bytes):
  1337. return value.decode("utf8")
  1338. # If it's listlike, convert it into a list of strings.
  1339. if hasattr(value, '__iter__'):
  1340. new_value = []
  1341. for v in value:
  1342. if (hasattr(v, '__iter__') and not isinstance(v, bytes)
  1343. and not isinstance(v, str)):
  1344. # This is almost certainly the user's mistake. In the
  1345. # interests of avoiding infinite loops, we'll let
  1346. # it through as-is rather than doing a recursive call.
  1347. new_value.append(v)
  1348. else:
  1349. new_value.append(self._normalize_search_value(v))
  1350. return new_value
  1351. # Otherwise, convert it into a Unicode string.
  1352. # The unicode(str()) thing is so this will do the same thing on Python 2
  1353. # and Python 3.
  1354. return str(str(value))
  1355. def __str__(self):
  1356. if self.text:
  1357. return self.text
  1358. else:
  1359. return "%s|%s" % (self.name, self.attrs)
  1360. def search_tag(self, markup_name=None, markup_attrs={}):
  1361. found = None
  1362. markup = None
  1363. if isinstance(markup_name, Tag):
  1364. markup = markup_name
  1365. markup_attrs = markup
  1366. call_function_with_tag_data = (
  1367. isinstance(self.name, collections.Callable)
  1368. and not isinstance(markup_name, Tag))
  1369. if ((not self.name)
  1370. or call_function_with_tag_data
  1371. or (markup and self._matches(markup, self.name))
  1372. or (not markup and self._matches(markup_name, self.name))):
  1373. if call_function_with_tag_data:
  1374. match = self.name(markup_name, markup_attrs)
  1375. else:
  1376. match = True
  1377. markup_attr_map = None
  1378. for attr, match_against in list(self.attrs.items()):
  1379. if not markup_attr_map:
  1380. if hasattr(markup_attrs, 'get'):
  1381. markup_attr_map = markup_attrs
  1382. else:
  1383. markup_attr_map = {}
  1384. for k, v in markup_attrs:
  1385. markup_attr_map[k] = v
  1386. attr_value = markup_attr_map.get(attr)
  1387. if not self._matches(attr_value, match_against):
  1388. match = False
  1389. break
  1390. if match:
  1391. if markup:
  1392. found = markup
  1393. else:
  1394. found = markup_name
  1395. if found and self.text and not self._matches(found.string, self.text):
  1396. found = None
  1397. return found
  1398. searchTag = search_tag
  1399. def search(self, markup):
  1400. # print 'looking for %s in %s' % (self, markup)
  1401. found = None
  1402. # If given a list of items, scan it for a text element that
  1403. # matches.
  1404. if hasattr(markup, '__iter__') and not isinstance(markup, (Tag, str)):
  1405. for element in markup:
  1406. if isinstance(element, NavigableString) \
  1407. and self.search(element):
  1408. found = element
  1409. break
  1410. # If it's a Tag, make sure its name or attributes match.
  1411. # Don't bother with Tags if we're searching for text.
  1412. elif isinstance(markup, Tag):
  1413. if not self.text or self.name or self.attrs:
  1414. found = self.search_tag(markup)
  1415. # If it's text, make sure the text matches.
  1416. elif isinstance(markup, NavigableString) or \
  1417. isinstance(markup, str):
  1418. if not self.name and not self.attrs and self._matches(markup, self.text):
  1419. found = markup
  1420. else:
  1421. raise Exception(
  1422. "I don't know how to match against a %s" % markup.__class__)
  1423. return found
  1424. def _matches(self, markup, match_against):
  1425. # print u"Matching %s against %s" % (markup, match_against)
  1426. result = False
  1427. if isinstance(markup, list) or isinstance(markup, tuple):
  1428. # This should only happen when searching a multi-valued attribute
  1429. # like 'class'.
  1430. if (isinstance(match_against, str)
  1431. and ' ' in match_against):
  1432. # A bit of a special case. If they try to match "foo
  1433. # bar" on a multivalue attribute's value, only accept
  1434. # the literal value "foo bar"
  1435. #
  1436. # XXX This is going to be pretty slow because we keep
  1437. # splitting match_against. But it shouldn't come up
  1438. # too often.
  1439. return (whitespace_re.split(match_against) == markup)
  1440. else:
  1441. for item in markup:
  1442. if self._matches(item, match_against):
  1443. return True
  1444. return False
  1445. if match_against is True:
  1446. # True matches any non-None value.
  1447. return markup is not None
  1448. if isinstance(match_against, collections.Callable):
  1449. return match_against(markup)
  1450. # Custom callables take the tag as an argument, but all
  1451. # other ways of matching match the tag name as a string.
  1452. if isinstance(markup, Tag):
  1453. markup = markup.name
  1454. # Ensure that `markup` is either a Unicode string, or None.
  1455. markup = self._normalize_search_value(markup)
  1456. if markup is None:
  1457. # None matches None, False, an empty string, an empty list, and so on.
  1458. return not match_against
  1459. if isinstance(match_against, str):
  1460. # Exact string match
  1461. return markup == match_against
  1462. if hasattr(match_against, 'match'):
  1463. # Regexp match
  1464. return match_against.search(markup)
  1465. if hasattr(match_against, '__iter__'):
  1466. # The markup must be an exact match against something
  1467. # in the iterable.
  1468. return markup in match_against
  1469. class ResultSet(list):
  1470. """A ResultSet is just a list that keeps track of the SoupStrainer
  1471. that created it."""
  1472. def __init__(self, source, result=()):
  1473. super(ResultSet, self).__init__(result)
  1474. self.source = source