element.py 64 KB

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