element.py 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211
  1. from __future__ import annotations
  2. # Use of this source code is governed by the MIT license.
  3. __license__ = "MIT"
  4. import re
  5. import warnings
  6. from bs4.css import CSS
  7. from bs4._deprecation import (
  8. _deprecated,
  9. _deprecated_alias,
  10. _deprecated_function_alias,
  11. )
  12. from bs4.formatter import (
  13. Formatter,
  14. HTMLFormatter,
  15. XMLFormatter,
  16. )
  17. from bs4._warnings import AttributeResemblesVariableWarning
  18. from typing import (
  19. Any,
  20. Callable,
  21. Dict,
  22. Generic,
  23. Iterable,
  24. Iterator,
  25. List,
  26. Mapping,
  27. MutableSequence,
  28. Optional,
  29. Pattern,
  30. Set,
  31. TYPE_CHECKING,
  32. Tuple,
  33. Type,
  34. TypeVar,
  35. Union,
  36. cast,
  37. overload,
  38. )
  39. from typing_extensions import (
  40. Self,
  41. TypeAlias,
  42. )
  43. if TYPE_CHECKING:
  44. from bs4 import BeautifulSoup
  45. from bs4.builder import TreeBuilder
  46. from bs4.filter import ElementFilter
  47. from bs4.formatter import (
  48. _EntitySubstitutionFunction,
  49. _FormatterOrName,
  50. )
  51. from bs4._typing import (
  52. _AtMostOneElement,
  53. _AtMostOneTag,
  54. _AtMostOneNavigableString,
  55. _AttributeValue,
  56. _AttributeValues,
  57. _Encoding,
  58. _InsertableElement,
  59. _OneElement,
  60. _QueryResults,
  61. _RawOrProcessedAttributeValues,
  62. _StrainableElement,
  63. _StrainableAttribute,
  64. _StrainableAttributes,
  65. _StrainableString,
  66. _SomeNavigableStrings,
  67. _SomeTags,
  68. )
  69. _OneOrMoreStringTypes: TypeAlias = Union[
  70. Type["NavigableString"], Iterable[Type["NavigableString"]]
  71. ]
  72. _FindMethodName: TypeAlias = Optional[Union["_StrainableElement", "ElementFilter"]]
  73. # Deprecated module-level attributes.
  74. # See https://peps.python.org/pep-0562/
  75. _deprecated_names = dict(
  76. whitespace_re="The {name} attribute was deprecated in version 4.7.0. If you need it, make your own copy."
  77. )
  78. #: :meta private:
  79. _deprecated_whitespace_re: Pattern[str] = re.compile(r"\s+")
  80. def __getattr__(name: str) -> Any:
  81. if name in _deprecated_names:
  82. message = _deprecated_names[name]
  83. warnings.warn(message.format(name=name), DeprecationWarning, stacklevel=2)
  84. return globals()[f"_deprecated_{name}"]
  85. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  86. #: Documents output by Beautiful Soup will be encoded with
  87. #: this encoding unless you specify otherwise.
  88. DEFAULT_OUTPUT_ENCODING: str = "utf-8"
  89. #: A regular expression that can be used to split on whitespace.
  90. nonwhitespace_re: Pattern[str] = re.compile(r"\S+")
  91. #: These encodings are recognized by Python (so `Tag.encode`
  92. #: could theoretically support them) but XML and HTML don't recognize
  93. #: them (so they should not show up in an XML or HTML document as that
  94. #: document's encoding).
  95. #:
  96. #: If an XML document is encoded in one of these encodings, no encoding
  97. #: will be mentioned in the XML declaration. If an HTML document is
  98. #: encoded in one of these encodings, and the HTML document has a
  99. #: <meta> tag that mentions an encoding, the encoding will be given as
  100. #: the empty string.
  101. #:
  102. #: Source:
  103. #: Python documentation, `Python Specific Encodings <https://docs.python.org/3/library/codecs.html#python-specific-encodings>`_
  104. PYTHON_SPECIFIC_ENCODINGS: Set[_Encoding] = set(
  105. [
  106. "idna",
  107. "mbcs",
  108. "oem",
  109. "palmos",
  110. "punycode",
  111. "raw_unicode_escape",
  112. "undefined",
  113. "unicode_escape",
  114. "raw-unicode-escape",
  115. "unicode-escape",
  116. "string-escape",
  117. "string_escape",
  118. ]
  119. )
  120. class NamespacedAttribute(str):
  121. """A namespaced attribute (e.g. the 'xml:lang' in 'xml:lang="en"')
  122. which remembers the namespace prefix ('xml') and the name ('lang')
  123. that were used to create it.
  124. """
  125. prefix: Optional[str]
  126. name: Optional[str]
  127. namespace: Optional[str]
  128. def __new__(
  129. cls,
  130. prefix: Optional[str],
  131. name: Optional[str] = None,
  132. namespace: Optional[str] = None,
  133. ) -> Self:
  134. if not name:
  135. # This is the default namespace. Its name "has no value"
  136. # per https://www.w3.org/TR/xml-names/#defaulting
  137. name = None
  138. if not name:
  139. obj = str.__new__(cls, prefix)
  140. elif not prefix:
  141. # Not really namespaced.
  142. obj = str.__new__(cls, name)
  143. else:
  144. obj = str.__new__(cls, prefix + ":" + name)
  145. obj.prefix = prefix
  146. obj.name = name
  147. obj.namespace = namespace
  148. return obj
  149. class AttributeValueWithCharsetSubstitution(str):
  150. """An abstract class standing in for a character encoding specified
  151. inside an HTML ``<meta>`` tag.
  152. Subclasses exist for each place such a character encoding might be
  153. found: either inside the ``charset`` attribute
  154. (`CharsetMetaAttributeValue`) or inside the ``content`` attribute
  155. (`ContentMetaAttributeValue`)
  156. This allows Beautiful Soup to replace that part of the HTML file
  157. with a different encoding when ouputting a tree as a string.
  158. """
  159. # The original, un-encoded value of the ``content`` attribute.
  160. #: :meta private:
  161. original_value: str
  162. def substitute_encoding(self, eventual_encoding: str) -> str:
  163. """Do whatever's necessary in this implementation-specific
  164. portion an HTML document to substitute in a specific encoding.
  165. """
  166. raise NotImplementedError()
  167. class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution):
  168. """A generic stand-in for the value of a ``<meta>`` tag's ``charset``
  169. attribute.
  170. When Beautiful Soup parses the markup ``<meta charset="utf8">``, the
  171. value of the ``charset`` attribute will become one of these objects.
  172. If the document is later encoded to an encoding other than UTF-8, its
  173. ``<meta>`` tag will mention the new encoding instead of ``utf8``.
  174. """
  175. def __new__(cls, original_value: str) -> Self:
  176. # We don't need to use the original value for anything, but
  177. # it might be useful for the user to know.
  178. obj = str.__new__(cls, original_value)
  179. obj.original_value = original_value
  180. return obj
  181. def substitute_encoding(self, eventual_encoding: _Encoding = "utf-8") -> str:
  182. """When an HTML document is being encoded to a given encoding, the
  183. value of a ``<meta>`` tag's ``charset`` becomes the name of
  184. the encoding.
  185. """
  186. if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS:
  187. return ""
  188. return eventual_encoding
  189. class AttributeValueList(List[str]):
  190. """Class for the list used to hold the values of attributes which
  191. have multiple values (such as HTML's 'class'). It's just a regular
  192. list, but you can subclass it and pass it in to the TreeBuilder
  193. constructor as attribute_value_list_class, to have your subclass
  194. instantiated instead.
  195. """
  196. class AttributeDict(Dict[Any,Any]):
  197. """Superclass for the dictionary used to hold a tag's
  198. attributes. You can use this, but it's just a regular dict with no
  199. special logic.
  200. """
  201. class XMLAttributeDict(AttributeDict):
  202. """A dictionary for holding a Tag's attributes, which processes
  203. incoming values for consistency with the HTML spec.
  204. """
  205. def __setitem__(self, key: str, value: Any) -> None:
  206. """Set an attribute value, possibly modifying it to comply with
  207. the XML spec.
  208. This just means converting common non-string values to
  209. strings: XML attributes may have "any literal string as a
  210. value."
  211. """
  212. if value is None:
  213. value = ""
  214. if isinstance(value, bool):
  215. # XML does not define any rules for boolean attributes.
  216. # Preserve the old Beautiful Soup behavior (a bool that
  217. # gets converted to a string on output) rather than
  218. # guessing what the value should be.
  219. pass
  220. elif isinstance(value, (int, float)):
  221. # It's dangerous to convert _every_ attribute value into a
  222. # plain string, since an attribute value may be a more
  223. # sophisticated string-like object
  224. # (e.g. CharsetMetaAttributeValue). But we can definitely
  225. # convert numeric values and booleans, which are the most common.
  226. value = str(value)
  227. super().__setitem__(key, value)
  228. class HTMLAttributeDict(AttributeDict):
  229. """A dictionary for holding a Tag's attributes, which processes
  230. incoming values for consistency with the HTML spec, which says
  231. 'Attribute values are a mixture of text and character
  232. references...'
  233. Basically, this means converting common non-string values into
  234. strings, like XMLAttributeDict, though HTML also has some rules
  235. around boolean attributes that XML doesn't have.
  236. """
  237. def __setitem__(self, key: str, value: Any) -> None:
  238. """Set an attribute value, possibly modifying it to comply
  239. with the HTML spec,
  240. """
  241. if value in (False, None):
  242. # 'The values "true" and "false" are not allowed on
  243. # boolean attributes. To represent a false value, the
  244. # attribute has to be omitted altogether.'
  245. if key in self:
  246. del self[key]
  247. return
  248. if isinstance(value, bool):
  249. # 'If the [boolean] attribute is present, its value must
  250. # either be the empty string or a value that is an ASCII
  251. # case-insensitive match for the attribute's canonical
  252. # name, with no leading or trailing whitespace.'
  253. #
  254. # [fixme] It's not clear to me whether "canonical name"
  255. # means fully-qualified name, unqualified name, or
  256. # (probably not) name with namespace prefix. For now I'm
  257. # going with unqualified name.
  258. if isinstance(key, NamespacedAttribute):
  259. value = key.name
  260. else:
  261. value = key
  262. elif isinstance(value, (int, float)):
  263. # See note in XMLAttributeDict for the reasoning why we
  264. # only do this to numbers.
  265. value = str(value)
  266. super().__setitem__(key, value)
  267. class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution):
  268. """A generic stand-in for the value of a ``<meta>`` tag's ``content``
  269. attribute.
  270. When Beautiful Soup parses the markup:
  271. ``<meta http-equiv="content-type" content="text/html; charset=utf8">``
  272. The value of the ``content`` attribute will become one of these objects.
  273. If the document is later encoded to an encoding other than UTF-8, its
  274. ``<meta>`` tag will mention the new encoding instead of ``utf8``.
  275. """
  276. #: Match the 'charset' argument inside the 'content' attribute
  277. #: of a <meta> tag.
  278. #: :meta private:
  279. CHARSET_RE: Pattern[str] = re.compile(r"((^|;)\s*charset=)([^;]*)", re.M)
  280. def __new__(cls, original_value: str) -> Self:
  281. cls.CHARSET_RE.search(original_value)
  282. obj = str.__new__(cls, original_value)
  283. obj.original_value = original_value
  284. return obj
  285. def substitute_encoding(self, eventual_encoding: _Encoding = "utf-8") -> str:
  286. """When an HTML document is being encoded to a given encoding, the
  287. value of the ``charset=`` in a ``<meta>`` tag's ``content`` becomes
  288. the name of the encoding.
  289. """
  290. if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS:
  291. return self.CHARSET_RE.sub("", self.original_value)
  292. def rewrite(match: re.Match[str]) -> str:
  293. return match.group(1) + eventual_encoding
  294. return self.CHARSET_RE.sub(rewrite, self.original_value)
  295. class PageElement(object):
  296. """An abstract class representing a single element in the parse tree.
  297. `NavigableString`, `Tag`, etc. are all subclasses of
  298. `PageElement`. For this reason you'll see a lot of methods that
  299. return `PageElement`, but you'll never see an actual `PageElement`
  300. object. For the most part you can think of `PageElement` as
  301. meaning "a `Tag` or a `NavigableString`."
  302. """
  303. #: In general, we can't tell just by looking at an element whether
  304. #: it's contained in an XML document or an HTML document. But for
  305. #: `Tag` objects (q.v.) we can store this information at parse time.
  306. #: :meta private:
  307. known_xml: Optional[bool] = None
  308. #: Whether or not this element has been decomposed from the tree
  309. #: it was created in.
  310. _decomposed: bool
  311. parent: Optional[Tag]
  312. next_element: _AtMostOneElement
  313. previous_element: _AtMostOneElement
  314. next_sibling: _AtMostOneElement
  315. previous_sibling: _AtMostOneElement
  316. #: Whether or not this element is hidden from generated output.
  317. #: Only the `BeautifulSoup` object itself is hidden.
  318. hidden: bool = False
  319. def setup(
  320. self,
  321. parent: Optional[Tag] = None,
  322. previous_element: _AtMostOneElement = None,
  323. next_element: _AtMostOneElement = None,
  324. previous_sibling: _AtMostOneElement = None,
  325. next_sibling: _AtMostOneElement = None,
  326. ) -> None:
  327. """Sets up the initial relations between this element and
  328. other elements.
  329. :param parent: The parent of this element.
  330. :param previous_element: The element parsed immediately before
  331. this one.
  332. :param next_element: The element parsed immediately after
  333. this one.
  334. :param previous_sibling: The most recently encountered element
  335. on the same level of the parse tree as this one.
  336. :param previous_sibling: The next element to be encountered
  337. on the same level of the parse tree as this one.
  338. """
  339. self.parent = parent
  340. self.previous_element = previous_element
  341. if self.previous_element is not None:
  342. self.previous_element.next_element = self
  343. self.next_element = next_element
  344. if self.next_element is not None:
  345. self.next_element.previous_element = self
  346. self.next_sibling = next_sibling
  347. if self.next_sibling is not None:
  348. self.next_sibling.previous_sibling = self
  349. if (
  350. previous_sibling is None
  351. and self.parent is not None
  352. and self.parent.contents
  353. ):
  354. previous_sibling = self.parent.contents[-1]
  355. self.previous_sibling = previous_sibling
  356. if self.previous_sibling is not None:
  357. self.previous_sibling.next_sibling = self
  358. def format_string(self, s: str, formatter: Optional[_FormatterOrName]) -> str:
  359. """Format the given string using the given formatter.
  360. :param s: A string.
  361. :param formatter: A Formatter object, or a string naming one of the standard formatters.
  362. """
  363. if formatter is None:
  364. return s
  365. if not isinstance(formatter, Formatter):
  366. formatter = self.formatter_for_name(formatter)
  367. output = formatter.substitute(s)
  368. return output
  369. def formatter_for_name(
  370. self, formatter_name: Union[_FormatterOrName, _EntitySubstitutionFunction]
  371. ) -> Formatter:
  372. """Look up or create a Formatter for the given identifier,
  373. if necessary.
  374. :param formatter: Can be a `Formatter` object (used as-is), a
  375. function (used as the entity substitution hook for an
  376. `bs4.formatter.XMLFormatter` or
  377. `bs4.formatter.HTMLFormatter`), or a string (used to look
  378. up an `bs4.formatter.XMLFormatter` or
  379. `bs4.formatter.HTMLFormatter` in the appropriate registry.
  380. """
  381. if isinstance(formatter_name, Formatter):
  382. return formatter_name
  383. c: type[Formatter]
  384. registry: Mapping[Optional[str], Formatter]
  385. if self._is_xml:
  386. c = XMLFormatter
  387. registry = XMLFormatter.REGISTRY
  388. else:
  389. c = HTMLFormatter
  390. registry = HTMLFormatter.REGISTRY
  391. if callable(formatter_name):
  392. return c(entity_substitution=formatter_name)
  393. return registry[formatter_name]
  394. @property
  395. def _is_xml(self) -> bool:
  396. """Is this element part of an XML tree or an HTML tree?
  397. This is used in formatter_for_name, when deciding whether an
  398. XMLFormatter or HTMLFormatter is more appropriate. It can be
  399. inefficient, but it should be called very rarely.
  400. """
  401. if self.known_xml is not None:
  402. # Most of the time we will have determined this when the
  403. # document is parsed.
  404. return self.known_xml
  405. # Otherwise, it's likely that this element was created by
  406. # direct invocation of the constructor from within the user's
  407. # Python code.
  408. if self.parent is None:
  409. # This is the top-level object. It should have .known_xml set
  410. # from tree creation. If not, take a guess--BS is usually
  411. # used on HTML markup.
  412. return getattr(self, "is_xml", False)
  413. return self.parent._is_xml
  414. nextSibling = _deprecated_alias("nextSibling", "next_sibling", "4.0.0")
  415. previousSibling = _deprecated_alias("previousSibling", "previous_sibling", "4.0.0")
  416. def __deepcopy__(self, memo: Dict[Any, Any], recursive: bool = False) -> Self:
  417. raise NotImplementedError()
  418. def __copy__(self) -> Self:
  419. """A copy of a PageElement can only be a deep copy, because
  420. only one PageElement can occupy a given place in a parse tree.
  421. """
  422. return self.__deepcopy__({})
  423. default: Iterable[type[NavigableString]] = tuple() #: :meta private:
  424. def _all_strings(
  425. self, strip: bool = False, types: Iterable[type[NavigableString]] = default
  426. ) -> Iterator[str]:
  427. """Yield all strings of certain classes, possibly stripping them.
  428. This is implemented differently in `Tag` and `NavigableString`.
  429. """
  430. raise NotImplementedError()
  431. @property
  432. def stripped_strings(self) -> Iterator[str]:
  433. """Yield all interesting strings in this PageElement, stripping them
  434. first.
  435. See `Tag` for information on which strings are considered
  436. interesting in a given context.
  437. """
  438. for string in self._all_strings(True):
  439. yield string
  440. def get_text(
  441. self,
  442. separator: str = "",
  443. strip: bool = False,
  444. types: Iterable[Type[NavigableString]] = default,
  445. ) -> str:
  446. """Get all child strings of this PageElement, concatenated using the
  447. given separator.
  448. :param separator: Strings will be concatenated using this separator.
  449. :param strip: If True, strings will be stripped before being
  450. concatenated.
  451. :param types: A tuple of NavigableString subclasses. Any
  452. strings of a subclass not found in this list will be
  453. ignored. Although there are exceptions, the default
  454. behavior in most cases is to consider only NavigableString
  455. and CData objects. That means no comments, processing
  456. instructions, etc.
  457. :return: A string.
  458. """
  459. return separator.join([s for s in self._all_strings(strip, types=types)])
  460. getText = get_text
  461. text = property(get_text)
  462. def replace_with(self, *args: _InsertableElement) -> Self:
  463. """Replace this `PageElement` with one or more other elements,
  464. objects, keeping the rest of the tree the same.
  465. :return: This `PageElement`, no longer part of the tree.
  466. """
  467. if self.parent is None:
  468. raise ValueError(
  469. "Cannot replace one element with another when the "
  470. "element to be replaced is not part of a tree."
  471. )
  472. if len(args) == 1 and args[0] is self:
  473. # Replacing an element with itself is a no-op.
  474. return self
  475. if any(x is self.parent for x in args):
  476. raise ValueError("Cannot replace a Tag with its parent.")
  477. old_parent = self.parent
  478. my_index = self.parent.index(self)
  479. self.extract(_self_index=my_index)
  480. for idx, replace_with in enumerate(args, start=my_index):
  481. old_parent.insert(idx, replace_with)
  482. return self
  483. replaceWith = _deprecated_function_alias("replaceWith", "replace_with", "4.0.0")
  484. def wrap(self, wrap_inside: Tag) -> Tag:
  485. """Wrap this `PageElement` inside a `Tag`.
  486. :return: ``wrap_inside``, occupying the position in the tree that used
  487. to be occupied by this object, and with this object now inside it.
  488. """
  489. me = self.replace_with(wrap_inside)
  490. wrap_inside.append(me)
  491. return wrap_inside
  492. def extract(self, _self_index: Optional[int] = None) -> Self:
  493. """Destructively rips this element out of the tree.
  494. :param _self_index: The location of this element in its parent's
  495. .contents, if known. Passing this in allows for a performance
  496. optimization.
  497. :return: this `PageElement`, no longer part of the tree.
  498. """
  499. if self.parent is not None:
  500. if _self_index is None:
  501. _self_index = self.parent.index(self)
  502. del self.parent.contents[_self_index]
  503. # Find the two elements that would be next to each other if
  504. # this element (and any children) hadn't been parsed. Connect
  505. # the two.
  506. last_child = self._last_descendant()
  507. # last_child can't be None because we passed accept_self=True
  508. # into _last_descendant. Worst case, last_child will be
  509. # self. Making this cast removes several mypy complaints later
  510. # on as we manipulate last_child.
  511. last_child = cast(PageElement, last_child)
  512. next_element = last_child.next_element
  513. if self.previous_element is not None:
  514. if self.previous_element is not next_element:
  515. self.previous_element.next_element = next_element
  516. if next_element is not None and next_element is not self.previous_element:
  517. next_element.previous_element = self.previous_element
  518. self.previous_element = None
  519. last_child.next_element = None
  520. self.parent = None
  521. if (
  522. self.previous_sibling is not None
  523. and self.previous_sibling is not self.next_sibling
  524. ):
  525. self.previous_sibling.next_sibling = self.next_sibling
  526. if (
  527. self.next_sibling is not None
  528. and self.next_sibling is not self.previous_sibling
  529. ):
  530. self.next_sibling.previous_sibling = self.previous_sibling
  531. self.previous_sibling = self.next_sibling = None
  532. return self
  533. def decompose(self) -> None:
  534. """Recursively destroys this `PageElement` and its children.
  535. The element will be removed from the tree and wiped out; so
  536. will everything beneath it.
  537. The behavior of a decomposed `PageElement` is undefined and you
  538. should never use one for anything, but if you need to *check*
  539. whether an element has been decomposed, you can use the
  540. `PageElement.decomposed` property.
  541. """
  542. self.extract()
  543. e: _AtMostOneElement = self
  544. next_up: _AtMostOneElement = None
  545. while e is not None:
  546. next_up = e.next_element
  547. e.__dict__.clear()
  548. if isinstance(e, Tag):
  549. e.name = ""
  550. e.contents = []
  551. e._decomposed = True
  552. e = next_up
  553. def _last_descendant(
  554. self, is_initialized: bool = True, accept_self: bool = True
  555. ) -> _AtMostOneElement:
  556. """Finds the last element beneath this object to be parsed.
  557. Special note to help you figure things out if your type
  558. checking is tripped up by the fact that this method returns
  559. _AtMostOneElement instead of PageElement: the only time
  560. this method returns None is if `accept_self` is False and the
  561. `PageElement` has no children--either it's a NavigableString
  562. or an empty Tag.
  563. :param is_initialized: Has `PageElement.setup` been called on
  564. this `PageElement` yet?
  565. :param accept_self: Is ``self`` an acceptable answer to the
  566. question?
  567. """
  568. if is_initialized and self.next_sibling is not None:
  569. last_child = self.next_sibling.previous_element
  570. else:
  571. last_child = self
  572. while isinstance(last_child, Tag) and last_child.contents:
  573. last_child = last_child.contents[-1]
  574. if not accept_self and last_child is self:
  575. last_child = None
  576. return last_child
  577. _lastRecursiveChild = _deprecated_alias(
  578. "_lastRecursiveChild", "_last_descendant", "4.0.0"
  579. )
  580. def insert_before(self, *args: _InsertableElement) -> List[PageElement]:
  581. """Makes the given element(s) the immediate predecessor of this one.
  582. All the elements will have the same `PageElement.parent` as
  583. this one, and the given elements will occur immediately before
  584. this one.
  585. :param args: One or more PageElements.
  586. :return The list of PageElements that were inserted.
  587. """
  588. parent = self.parent
  589. if parent is None:
  590. raise ValueError("Element has no parent, so 'before' has no meaning.")
  591. if any(x is self for x in args):
  592. raise ValueError("Can't insert an element before itself.")
  593. results: List[PageElement] = []
  594. for predecessor in args:
  595. # Extract first so that the index won't be screwed up if they
  596. # are siblings.
  597. if isinstance(predecessor, PageElement):
  598. predecessor.extract()
  599. index = parent.index(self)
  600. results.extend(parent.insert(index, predecessor))
  601. return results
  602. def insert_after(self, *args: _InsertableElement) -> List[PageElement]:
  603. """Makes the given element(s) the immediate successor of this one.
  604. The elements will have the same `PageElement.parent` as this
  605. one, and the given elements will occur immediately after this
  606. one.
  607. :param args: One or more PageElements.
  608. :return The list of PageElements that were inserted.
  609. """
  610. # Do all error checking before modifying the tree.
  611. parent = self.parent
  612. if parent is None:
  613. raise ValueError("Element has no parent, so 'after' has no meaning.")
  614. if any(x is self for x in args):
  615. raise ValueError("Can't insert an element after itself.")
  616. offset = 0
  617. results: List[PageElement] = []
  618. for successor in args:
  619. # Extract first so that the index won't be screwed up if they
  620. # are siblings.
  621. if isinstance(successor, PageElement):
  622. successor.extract()
  623. index = parent.index(self)
  624. results.extend(parent.insert(index + 1 + offset, successor))
  625. offset += 1
  626. return results
  627. # For the suppression of this pyright warning, see discussion here:
  628. # https://github.com/microsoft/pyright/issues/10929
  629. @overload
  630. def find_next( # pyright: ignore [reportOverlappingOverload]
  631. self,
  632. name: _FindMethodName = None,
  633. attrs: Optional[_StrainableAttributes] = None,
  634. string: None=None,
  635. **kwargs: _StrainableAttribute,
  636. ) -> _AtMostOneTag:
  637. ...
  638. @overload
  639. def find_next(
  640. self,
  641. name: None=None,
  642. attrs: None=None,
  643. string: _StrainableString="",
  644. **kwargs: _StrainableAttribute,
  645. ) -> _AtMostOneNavigableString:
  646. ...
  647. def find_next(
  648. self,
  649. name: _FindMethodName = None,
  650. attrs: Optional[_StrainableAttributes] = None,
  651. string: Optional[_StrainableString] = None,
  652. **kwargs: _StrainableAttribute,
  653. ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]:
  654. """Find the first PageElement that matches the given criteria and
  655. appears later in the document than this PageElement.
  656. All find_* methods take a common set of arguments. See the online
  657. documentation for detailed explanations.
  658. :param name: A filter on tag name.
  659. :param attrs: Additional filters on attribute values.
  660. :param string: A filter for a NavigableString with specific text.
  661. :kwargs: Additional filters on attribute values.
  662. """
  663. return self._find_one(self.find_all_next, name, attrs, string, **kwargs)
  664. findNext = _deprecated_function_alias("findNext", "find_next", "4.0.0")
  665. @overload
  666. def find_all_next( # pyright: ignore [reportOverlappingOverload]
  667. self,
  668. name: _FindMethodName = None,
  669. attrs: Optional[_StrainableAttributes] = None,
  670. string: None = None,
  671. limit: Optional[int] = None,
  672. _stacklevel: int = 2,
  673. **kwargs: _StrainableAttribute,
  674. ) -> _SomeTags:
  675. ...
  676. @overload
  677. def find_all_next(
  678. self,
  679. name: None = None,
  680. attrs: None = None,
  681. string: _StrainableString = "",
  682. limit: Optional[int] = None,
  683. _stacklevel: int = 2,
  684. **kwargs: _StrainableAttribute,
  685. ) -> _SomeNavigableStrings:
  686. ...
  687. def find_all_next(
  688. self,
  689. name: _FindMethodName = None,
  690. attrs: Optional[_StrainableAttributes] = None,
  691. string: Optional[_StrainableString] = None,
  692. limit: Optional[int] = None,
  693. _stacklevel: int = 2,
  694. **kwargs: _StrainableAttribute,
  695. ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]:
  696. """Find all `PageElement` objects that match the given criteria and
  697. appear later in the document than this `PageElement`.
  698. All find_* methods take a common set of arguments. See the online
  699. documentation for detailed explanations.
  700. :param name: A filter on tag name.
  701. :param attrs: Additional filters on attribute values.
  702. :param string: A filter for a NavigableString with specific text.
  703. :param limit: Stop looking after finding this many results.
  704. :param _stacklevel: Used internally to improve warning messages.
  705. :kwargs: Additional filters on attribute values.
  706. """
  707. return self._find_all(
  708. name,
  709. attrs,
  710. string,
  711. limit,
  712. self.next_elements,
  713. _stacklevel=_stacklevel + 1,
  714. **kwargs,
  715. )
  716. findAllNext = _deprecated_function_alias("findAllNext", "find_all_next", "4.0.0")
  717. @overload
  718. def find_next_sibling( # pyright: ignore [reportOverlappingOverload]
  719. self,
  720. name: _FindMethodName = None,
  721. attrs: Optional[_StrainableAttributes] = None,
  722. string: None=None,
  723. **kwargs: _StrainableAttribute,
  724. ) -> _AtMostOneTag:
  725. ...
  726. @overload
  727. def find_next_sibling(
  728. self,
  729. name: None=None,
  730. attrs: None=None,
  731. string: _StrainableString="",
  732. **kwargs: _StrainableAttribute,
  733. ) -> _AtMostOneNavigableString:
  734. ...
  735. def find_next_sibling(
  736. self,
  737. name: _FindMethodName = None,
  738. attrs: Optional[_StrainableAttributes] = None,
  739. string: Optional[_StrainableString] = None,
  740. **kwargs: _StrainableAttribute,
  741. ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]:
  742. """Find the closest sibling to this PageElement that matches the
  743. given criteria and appears later in the document.
  744. All find_* methods take a common set of arguments. See the
  745. online documentation for detailed explanations.
  746. :param name: A filter on tag name.
  747. :param attrs: Additional filters on attribute values.
  748. :param string: A filter for a `NavigableString` with specific text.
  749. :kwargs: Additional filters on attribute values.
  750. """
  751. return self._find_one(self.find_next_siblings, name, attrs, string, **kwargs)
  752. findNextSibling = _deprecated_function_alias(
  753. "findNextSibling", "find_next_sibling", "4.0.0"
  754. )
  755. @overload
  756. def find_next_siblings( # pyright: ignore [reportOverlappingOverload]
  757. self,
  758. name: _FindMethodName = None,
  759. attrs: Optional[_StrainableAttributes] = None,
  760. string: None = None,
  761. limit: Optional[int] = None,
  762. _stacklevel: int = 2,
  763. **kwargs: _StrainableAttribute,
  764. ) -> _SomeTags:
  765. ...
  766. @overload
  767. def find_next_siblings(
  768. self,
  769. name: None = None,
  770. attrs: None = None,
  771. string: _StrainableString = "",
  772. limit: Optional[int] = None,
  773. _stacklevel: int = 2,
  774. **kwargs: _StrainableAttribute,
  775. ) -> _SomeNavigableStrings:
  776. ...
  777. def find_next_siblings(
  778. self,
  779. name: _FindMethodName = None,
  780. attrs: Optional[_StrainableAttributes] = None,
  781. string: Optional[_StrainableString] = None,
  782. limit: Optional[int] = None,
  783. _stacklevel: int = 2,
  784. **kwargs: _StrainableAttribute,
  785. ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]:
  786. """Find all siblings of this `PageElement` that match the given criteria
  787. and appear later in the document.
  788. All find_* methods take a common set of arguments. See the online
  789. documentation for detailed explanations.
  790. :param name: A filter on tag name.
  791. :param attrs: Additional filters on attribute values.
  792. :param string: A filter for a `NavigableString` with specific text.
  793. :param limit: Stop looking after finding this many results.
  794. :param _stacklevel: Used internally to improve warning messages.
  795. :kwargs: Additional filters on attribute values.
  796. """
  797. return self._find_all(
  798. name,
  799. attrs,
  800. string,
  801. limit,
  802. self.next_siblings,
  803. _stacklevel=_stacklevel + 1,
  804. **kwargs,
  805. )
  806. findNextSiblings = _deprecated_function_alias(
  807. "findNextSiblings", "find_next_siblings", "4.0.0"
  808. )
  809. fetchNextSiblings = _deprecated_function_alias(
  810. "fetchNextSiblings", "find_next_siblings", "3.0.0"
  811. )
  812. @overload
  813. def find_previous( # pyright: ignore [reportOverlappingOverload]
  814. self,
  815. name: _FindMethodName = None,
  816. attrs: Optional[_StrainableAttributes] = None,
  817. string: None=None,
  818. **kwargs: _StrainableAttribute,
  819. ) -> _AtMostOneTag:
  820. ...
  821. @overload
  822. def find_previous(
  823. self,
  824. name: None=None,
  825. attrs: None=None,
  826. string: _StrainableString="",
  827. **kwargs: _StrainableAttribute,
  828. ) -> _AtMostOneNavigableString:
  829. ...
  830. def find_previous(
  831. self,
  832. name: _FindMethodName = None,
  833. attrs: Optional[_StrainableAttributes] = None,
  834. string: Optional[_StrainableString] = None,
  835. **kwargs: _StrainableAttribute,
  836. ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]:
  837. """Look backwards in the document from this `PageElement` and find the
  838. first `PageElement` that matches the given criteria.
  839. All find_* methods take a common set of arguments. See the online
  840. documentation for detailed explanations.
  841. :param name: A filter on tag name.
  842. :param attrs: Additional filters on attribute values.
  843. :param string: A filter for a `NavigableString` with specific text.
  844. :kwargs: Additional filters on attribute values.
  845. """
  846. return self._find_one(self.find_all_previous, name, attrs, string, **kwargs)
  847. findPrevious = _deprecated_function_alias("findPrevious", "find_previous", "3.0.0")
  848. @overload
  849. def find_all_previous( # pyright: ignore [reportOverlappingOverload]
  850. self,
  851. name: _FindMethodName = None,
  852. attrs: Optional[_StrainableAttributes] = None,
  853. string: None = None,
  854. limit: Optional[int] = None,
  855. _stacklevel: int = 2,
  856. **kwargs: _StrainableAttribute,
  857. ) -> _SomeTags:
  858. ...
  859. @overload
  860. def find_all_previous(
  861. self,
  862. name: None = None,
  863. attrs: None = None,
  864. string: _StrainableString = "",
  865. limit: Optional[int] = None,
  866. _stacklevel: int = 2,
  867. **kwargs: _StrainableAttribute,
  868. ) -> _SomeNavigableStrings:
  869. ...
  870. def find_all_previous(
  871. self,
  872. name: _FindMethodName = None,
  873. attrs: Optional[_StrainableAttributes] = None,
  874. string: Optional[_StrainableString] = None,
  875. limit: Optional[int] = None,
  876. _stacklevel: int = 2,
  877. **kwargs: _StrainableAttribute,
  878. ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]:
  879. """Look backwards in the document from this `PageElement` and find all
  880. `PageElement` that match the given criteria.
  881. All find_* methods take a common set of arguments. See the online
  882. documentation for detailed explanations.
  883. :param name: A filter on tag name.
  884. :param attrs: Additional filters on attribute values.
  885. :param string: A filter for a `NavigableString` with specific text.
  886. :param limit: Stop looking after finding this many results.
  887. :param _stacklevel: Used internally to improve warning messages.
  888. :kwargs: Additional filters on attribute values.
  889. """
  890. return self._find_all(
  891. name,
  892. attrs,
  893. string,
  894. limit,
  895. self.previous_elements,
  896. _stacklevel=_stacklevel + 1,
  897. **kwargs,
  898. )
  899. findAllPrevious = _deprecated_function_alias(
  900. "findAllPrevious", "find_all_previous", "4.0.0"
  901. )
  902. fetchAllPrevious = _deprecated_function_alias(
  903. "fetchAllPrevious", "find_all_previous", "3.0.0"
  904. )
  905. @overload
  906. def find_previous_sibling( # pyright: ignore [reportOverlappingOverload]
  907. self,
  908. name: _FindMethodName = None,
  909. attrs: Optional[_StrainableAttributes] = None,
  910. string: None=None,
  911. **kwargs: _StrainableAttribute,
  912. ) -> _AtMostOneTag:
  913. ...
  914. @overload
  915. def find_previous_sibling(
  916. self,
  917. name: None=None,
  918. attrs: None=None,
  919. string: _StrainableString="",
  920. **kwargs: _StrainableAttribute,
  921. ) -> _AtMostOneNavigableString:
  922. ...
  923. def find_previous_sibling(
  924. self,
  925. name: _FindMethodName = None,
  926. attrs: Optional[_StrainableAttributes] = None,
  927. string: Optional[_StrainableString] = None,
  928. **kwargs: _StrainableAttribute,
  929. ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]:
  930. """Returns the closest sibling to this `PageElement` that matches the
  931. given criteria and appears earlier in the document.
  932. All find_* methods take a common set of arguments. See the online
  933. documentation for detailed explanations.
  934. :param name: A filter on tag name.
  935. :param attrs: Additional filters on attribute values.
  936. :param string: A filter for a `NavigableString` with specific text.
  937. :kwargs: Additional filters on attribute values.
  938. """
  939. return self._find_one(
  940. self.find_previous_siblings, name, attrs, string, **kwargs
  941. )
  942. findPreviousSibling = _deprecated_function_alias(
  943. "findPreviousSibling", "find_previous_sibling", "4.0.0"
  944. )
  945. @overload
  946. def find_previous_siblings( # pyright: ignore [reportOverlappingOverload]
  947. self,
  948. name: _FindMethodName = None,
  949. attrs: Optional[_StrainableAttributes] = None,
  950. string: None = None,
  951. limit: Optional[int] = None,
  952. _stacklevel: int = 2,
  953. **kwargs: _StrainableAttribute,
  954. ) -> _SomeTags:
  955. ...
  956. @overload
  957. def find_previous_siblings(
  958. self,
  959. name: None = None,
  960. attrs: None = None,
  961. string: _StrainableString = "",
  962. limit: Optional[int] = None,
  963. _stacklevel: int = 2,
  964. **kwargs: _StrainableAttribute,
  965. ) -> _SomeNavigableStrings:
  966. ...
  967. def find_previous_siblings(
  968. self,
  969. name: _FindMethodName = None,
  970. attrs: Optional[_StrainableAttributes] = None,
  971. string: Optional[_StrainableString] = None,
  972. limit: Optional[int] = None,
  973. _stacklevel: int = 2,
  974. **kwargs: _StrainableAttribute,
  975. ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]:
  976. """Returns all siblings to this PageElement that match the
  977. given criteria and appear earlier in the document.
  978. All find_* methods take a common set of arguments. See the online
  979. documentation for detailed explanations.
  980. :param name: A filter on tag name.
  981. :param attrs: Additional filters on attribute values.
  982. :param string: A filter for a NavigableString with specific text.
  983. :param limit: Stop looking after finding this many results.
  984. :param _stacklevel: Used internally to improve warning messages.
  985. :kwargs: Additional filters on attribute values.
  986. """
  987. return self._find_all(
  988. name,
  989. attrs,
  990. string,
  991. limit,
  992. self.previous_siblings,
  993. _stacklevel=_stacklevel + 1,
  994. **kwargs,
  995. )
  996. findPreviousSiblings = _deprecated_function_alias(
  997. "findPreviousSiblings", "find_previous_siblings", "4.0.0"
  998. )
  999. fetchPreviousSiblings = _deprecated_function_alias(
  1000. "fetchPreviousSiblings", "find_previous_siblings", "3.0.0"
  1001. )
  1002. def find_parent(
  1003. self,
  1004. name: _FindMethodName = None,
  1005. attrs: Optional[_StrainableAttributes] = None,
  1006. **kwargs: _StrainableAttribute,
  1007. ) -> _AtMostOneTag:
  1008. """Find the closest parent of this PageElement that matches the given
  1009. criteria.
  1010. All find_* methods take a common set of arguments. See the online
  1011. documentation for detailed explanations.
  1012. :param name: A filter on tag name.
  1013. :param attrs: Additional filters on attribute values.
  1014. :param self: Whether the PageElement itself should be considered
  1015. as one of its 'parents'.
  1016. :kwargs: Additional filters on attribute values.
  1017. """
  1018. # NOTE: We can't use _find_one because findParents takes a different
  1019. # set of arguments.
  1020. r = None
  1021. results = self.find_parents(
  1022. name, attrs, 1, _stacklevel=3, **kwargs
  1023. )
  1024. if results:
  1025. r = results[0]
  1026. return r
  1027. findParent = _deprecated_function_alias("findParent", "find_parent", "4.0.0")
  1028. def find_parents(
  1029. self,
  1030. name: _FindMethodName = None,
  1031. attrs: Optional[_StrainableAttributes] = None,
  1032. limit: Optional[int] = None,
  1033. _stacklevel: int = 2,
  1034. **kwargs: _StrainableAttribute,
  1035. ) -> _SomeTags:
  1036. """Find all parents of this `PageElement` that match the given criteria.
  1037. All find_* methods take a common set of arguments. See the online
  1038. documentation for detailed explanations.
  1039. :param name: A filter on tag name.
  1040. :param attrs: Additional filters on attribute values.
  1041. :param limit: Stop looking after finding this many results.
  1042. :param _stacklevel: Used internally to improve warning messages.
  1043. :kwargs: Additional filters on attribute values.
  1044. """
  1045. iterator = self.parents
  1046. # Only Tags can have children, so this ResultSet will contain
  1047. # nothing but Tags.
  1048. return cast(ResultSet[Tag], self._find_all(
  1049. name, attrs, None, limit, iterator, _stacklevel=_stacklevel + 1, **kwargs
  1050. ))
  1051. findParents = _deprecated_function_alias("findParents", "find_parents", "4.0.0")
  1052. fetchParents = _deprecated_function_alias("fetchParents", "find_parents", "3.0.0")
  1053. @property
  1054. def next(self) -> _AtMostOneElement:
  1055. """The `PageElement`, if any, that was parsed just after this one."""
  1056. return self.next_element
  1057. @property
  1058. def previous(self) -> _AtMostOneElement:
  1059. """The `PageElement`, if any, that was parsed just before this one."""
  1060. return self.previous_element
  1061. # These methods do the real heavy lifting.
  1062. def _find_one(
  1063. self,
  1064. # TODO-TYPING: "There is no syntax to indicate optional or
  1065. # keyword arguments; such function types are rarely used
  1066. # as callback types." - So, not sure how to get more
  1067. # specific here.
  1068. method: Callable,
  1069. name: _FindMethodName,
  1070. attrs: Optional[_StrainableAttributes],
  1071. string: Optional[_StrainableString],
  1072. **kwargs: _StrainableAttribute,
  1073. ) -> _AtMostOneElement:
  1074. r: _AtMostOneElement = None
  1075. results: _QueryResults = method(name, attrs, string, 1, _stacklevel=4, **kwargs)
  1076. if results:
  1077. r = results[0]
  1078. return r
  1079. def _find_all(
  1080. self,
  1081. name: _FindMethodName,
  1082. attrs: Optional[_StrainableAttributes],
  1083. string: Optional[_StrainableString],
  1084. limit: Optional[int],
  1085. generator: Iterator[PageElement],
  1086. _stacklevel: int = 3,
  1087. **kwargs: _StrainableAttribute,
  1088. ) -> _QueryResults:
  1089. """Iterates over a generator looking for things that match."""
  1090. if string is None and "text" in kwargs:
  1091. string = kwargs.pop("text")
  1092. warnings.warn(
  1093. "The 'text' argument to find()-type methods is deprecated. Use 'string' instead.",
  1094. DeprecationWarning,
  1095. stacklevel=_stacklevel,
  1096. )
  1097. if "_class" in kwargs:
  1098. warnings.warn(
  1099. AttributeResemblesVariableWarning.MESSAGE
  1100. % dict(
  1101. original="_class",
  1102. autocorrect="class_",
  1103. ),
  1104. AttributeResemblesVariableWarning,
  1105. stacklevel=_stacklevel,
  1106. )
  1107. from bs4.filter import ElementFilter
  1108. if isinstance(name, ElementFilter):
  1109. matcher = name
  1110. else:
  1111. matcher = SoupStrainer(name, attrs, string, **kwargs)
  1112. result: MutableSequence[_OneElement]
  1113. if string is None and not limit and not attrs and not kwargs:
  1114. if name is True or name is None:
  1115. # Optimization to find all tags.
  1116. result = [element for element in generator if isinstance(element, Tag)]
  1117. return ResultSet(matcher, result)
  1118. elif isinstance(name, str):
  1119. # Optimization to find all tags with a given name.
  1120. if name.count(":") == 1:
  1121. # This is a name with a prefix. If this is a namespace-aware document,
  1122. # we need to match the local name against tag.name. If not,
  1123. # we need to match the fully-qualified name against tag.name.
  1124. prefix, local_name = name.split(":", 1)
  1125. else:
  1126. prefix = None
  1127. local_name = name
  1128. result = []
  1129. for element in generator:
  1130. if not isinstance(element, Tag):
  1131. continue
  1132. if element.name == name or (
  1133. element.name == local_name
  1134. and (prefix is None or element.prefix == prefix)
  1135. ):
  1136. result.append(element)
  1137. return ResultSet(matcher, result)
  1138. return matcher.find_all(generator, limit)
  1139. # These generators can be used to navigate starting from both
  1140. # NavigableStrings and Tags.
  1141. @property
  1142. def next_elements(self) -> Iterator[PageElement]:
  1143. """All PageElements that were parsed after this one."""
  1144. i = self.next_element
  1145. while i is not None:
  1146. successor = i.next_element
  1147. yield i
  1148. i = successor
  1149. @property
  1150. def self_and_next_elements(self) -> Iterator[PageElement]:
  1151. """This PageElement, then all PageElements that were parsed after it."""
  1152. return self._self_and(self.next_elements)
  1153. @property
  1154. def next_siblings(self) -> Iterator[PageElement]:
  1155. """All PageElements that are siblings of this one but were parsed
  1156. later.
  1157. """
  1158. i = self.next_sibling
  1159. while i is not None:
  1160. successor = i.next_sibling
  1161. yield i
  1162. i = successor
  1163. @property
  1164. def self_and_next_siblings(self) -> Iterator[PageElement]:
  1165. """This PageElement, then all of its siblings."""
  1166. return self._self_and(self.next_siblings)
  1167. @property
  1168. def previous_elements(self) -> Iterator[PageElement]:
  1169. """All PageElements that were parsed before this one.
  1170. :yield: A sequence of PageElements.
  1171. """
  1172. i = self.previous_element
  1173. while i is not None:
  1174. successor = i.previous_element
  1175. yield i
  1176. i = successor
  1177. @property
  1178. def self_and_previous_elements(self) -> Iterator[PageElement]:
  1179. """This PageElement, then all elements that were parsed
  1180. earlier."""
  1181. return self._self_and(self.previous_elements)
  1182. @property
  1183. def previous_siblings(self) -> Iterator[PageElement]:
  1184. """All PageElements that are siblings of this one but were parsed
  1185. earlier.
  1186. :yield: A sequence of PageElements.
  1187. """
  1188. i = self.previous_sibling
  1189. while i is not None:
  1190. successor = i.previous_sibling
  1191. yield i
  1192. i = successor
  1193. @property
  1194. def self_and_previous_siblings(self) -> Iterator[PageElement]:
  1195. """This PageElement, then all of its siblings that were parsed
  1196. earlier."""
  1197. return self._self_and(self.previous_siblings)
  1198. @property
  1199. def parents(self) -> Iterator[Tag]:
  1200. """All elements that are parents of this PageElement.
  1201. :yield: A sequence of Tags, ending with a BeautifulSoup object.
  1202. """
  1203. i = self.parent
  1204. while i is not None:
  1205. successor = i.parent
  1206. yield i
  1207. i = successor
  1208. @property
  1209. def self_and_parents(self) -> Iterator[PageElement]:
  1210. """This element, then all of its parents.
  1211. :yield: A sequence of PageElements, ending with a BeautifulSoup object.
  1212. """
  1213. return self._self_and(self.parents)
  1214. def _self_and(self, other_generator:Iterator[PageElement]) -> Iterator[PageElement]:
  1215. """Modify a generator by yielding this element, then everything
  1216. yielded by the other generator.
  1217. """
  1218. if not self.hidden:
  1219. yield self
  1220. for i in other_generator:
  1221. yield i
  1222. @property
  1223. def decomposed(self) -> bool:
  1224. """Check whether a PageElement has been decomposed."""
  1225. return getattr(self, "_decomposed", False) or False
  1226. @_deprecated("next_elements", "4.0.0")
  1227. def nextGenerator(self) -> Iterator[PageElement]:
  1228. ":meta private:"
  1229. return self.next_elements
  1230. @_deprecated("next_siblings", "4.0.0")
  1231. def nextSiblingGenerator(self) -> Iterator[PageElement]:
  1232. ":meta private:"
  1233. return self.next_siblings
  1234. @_deprecated("previous_elements", "4.0.0")
  1235. def previousGenerator(self) -> Iterator[PageElement]:
  1236. ":meta private:"
  1237. return self.previous_elements
  1238. @_deprecated("previous_siblings", "4.0.0")
  1239. def previousSiblingGenerator(self) -> Iterator[PageElement]:
  1240. ":meta private:"
  1241. return self.previous_siblings
  1242. @_deprecated("parents", "4.0.0")
  1243. def parentGenerator(self) -> Iterator[PageElement]:
  1244. ":meta private:"
  1245. return self.parents
  1246. class NavigableString(str, PageElement):
  1247. """A Python string that is part of a parse tree.
  1248. When Beautiful Soup parses the markup ``<b>penguin</b>``, it will
  1249. create a `NavigableString` for the string "penguin".
  1250. """
  1251. #: A string prepended to the body of the 'real' string
  1252. #: when formatting it as part of a document, such as the '<!--'
  1253. #: in an HTML comment.
  1254. PREFIX: str = ""
  1255. #: A string appended to the body of the 'real' string
  1256. #: when formatting it as part of a document, such as the '-->'
  1257. #: in an HTML comment.
  1258. SUFFIX: str = ""
  1259. def __new__(cls, value: Union[str, bytes]) -> Self:
  1260. """Create a new NavigableString.
  1261. When unpickling a NavigableString, this method is called with
  1262. the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
  1263. passed in to the superclass's __new__ or the superclass won't know
  1264. how to handle non-ASCII characters.
  1265. """
  1266. if isinstance(value, str):
  1267. u = str.__new__(cls, value)
  1268. else:
  1269. u = str.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
  1270. u.hidden = False
  1271. u.setup()
  1272. return u
  1273. def __deepcopy__(self, memo: Dict[Any, Any], recursive: bool = False) -> Self:
  1274. """A copy of a NavigableString has the same contents and class
  1275. as the original, but it is not connected to the parse tree.
  1276. :param recursive: This parameter is ignored; it's only defined
  1277. so that NavigableString.__deepcopy__ implements the same
  1278. signature as Tag.__deepcopy__.
  1279. """
  1280. return type(self)(self)
  1281. def __getnewargs__(self) -> Tuple[str]:
  1282. return (str(self),)
  1283. # TODO-TYPING This should be SupportsIndex|slice but SupportsIndex
  1284. # is introduced in 3.8. This can be changed once 3.7 support is dropped.
  1285. def __getitem__(self, key: Union[int|slice]) -> str: # type:ignore
  1286. """Raise an exception """
  1287. if isinstance(key, str):
  1288. raise TypeError("string indices must be integers, not '{0}'. Are you treating a NavigableString like a Tag?".format(key.__class__.__name__))
  1289. return super(NavigableString, self).__getitem__(key)
  1290. @property
  1291. def string(self) -> str:
  1292. """Convenience property defined to match `Tag.string`.
  1293. :return: This property always returns the `NavigableString` it was
  1294. called on.
  1295. :meta private:
  1296. """
  1297. return self
  1298. def output_ready(self, formatter: _FormatterOrName = "minimal") -> str:
  1299. """Run the string through the provided formatter, making it
  1300. ready for output as part of an HTML or XML document.
  1301. :param formatter: A `Formatter` object, or a string naming one
  1302. of the standard formatters.
  1303. """
  1304. output = self.format_string(self, formatter)
  1305. return self.PREFIX + output + self.SUFFIX
  1306. @property
  1307. def name(self) -> None:
  1308. """Since a NavigableString is not a Tag, it has no .name.
  1309. This property is implemented so that code like this doesn't crash
  1310. when run on a mixture of Tag and NavigableString objects:
  1311. [x.name for x in tag.children]
  1312. :meta private:
  1313. """
  1314. return None
  1315. @name.setter
  1316. def name(self, name: str) -> None:
  1317. """Prevent NavigableString.name from ever being set.
  1318. :meta private:
  1319. """
  1320. raise AttributeError("A NavigableString cannot be given a name.")
  1321. def _all_strings(
  1322. self, strip: bool = False, types: _OneOrMoreStringTypes = PageElement.default
  1323. ) -> Iterator[str]:
  1324. """Yield all strings of certain classes, possibly stripping them.
  1325. This makes it easy for NavigableString to implement methods
  1326. like get_text() as conveniences, creating a consistent
  1327. text-extraction API across all PageElements.
  1328. :param strip: If True, all strings will be stripped before being
  1329. yielded.
  1330. :param types: A tuple of NavigableString subclasses. If this
  1331. NavigableString isn't one of those subclasses, the
  1332. sequence will be empty. By default, the subclasses
  1333. considered are NavigableString and CData objects. That
  1334. means no comments, processing instructions, etc.
  1335. :yield: A sequence that either contains this string, or is empty.
  1336. """
  1337. if types is self.default:
  1338. # This is kept in Tag because it's full of subclasses of
  1339. # this class, which aren't defined until later in the file.
  1340. types = Tag.MAIN_CONTENT_STRING_TYPES
  1341. # Do nothing if the caller is looking for specific types of
  1342. # string, and we're of a different type.
  1343. #
  1344. # We check specific types instead of using isinstance(self,
  1345. # types) because all of these classes subclass
  1346. # NavigableString. Anyone who's using this feature probably
  1347. # wants generic NavigableStrings but not other stuff.
  1348. my_type = type(self)
  1349. if types is not None:
  1350. if isinstance(types, type):
  1351. # Looking for a single type.
  1352. if my_type is not types:
  1353. return
  1354. elif my_type not in types:
  1355. # Looking for one of a list of types.
  1356. return
  1357. value = self
  1358. if strip:
  1359. final_value = value.strip()
  1360. else:
  1361. final_value = self
  1362. if len(final_value) > 0:
  1363. yield final_value
  1364. @property
  1365. def strings(self) -> Iterator[str]:
  1366. """Yield this string, but only if it is interesting.
  1367. This is defined the way it is for compatibility with
  1368. `Tag.strings`. See `Tag` for information on which strings are
  1369. interesting in a given context.
  1370. :yield: A sequence that either contains this string, or is empty.
  1371. """
  1372. return self._all_strings()
  1373. class PreformattedString(NavigableString):
  1374. """A `NavigableString` not subject to the normal formatting rules.
  1375. This is an abstract class used for special kinds of strings such
  1376. as comments (`Comment`) and CDATA blocks (`CData`).
  1377. """
  1378. PREFIX: str = ""
  1379. SUFFIX: str = ""
  1380. def output_ready(self, formatter: Optional[_FormatterOrName] = None) -> str:
  1381. """Make this string ready for output by adding any subclass-specific
  1382. prefix or suffix.
  1383. :param formatter: A `Formatter` object, or a string naming one
  1384. of the standard formatters. The string will be passed into the
  1385. `Formatter`, but only to trigger any side effects: the return
  1386. value is ignored.
  1387. :return: The string, with any subclass-specific prefix and
  1388. suffix added on.
  1389. """
  1390. if formatter is not None:
  1391. self.format_string(self, formatter)
  1392. return self.PREFIX + self + self.SUFFIX
  1393. class CData(PreformattedString):
  1394. """A `CDATA section <https://dev.w3.org/html5/spec-LC/syntax.html#cdata-sections>`_."""
  1395. PREFIX: str = "<![CDATA["
  1396. SUFFIX: str = "]]>"
  1397. class ProcessingInstruction(PreformattedString):
  1398. """A SGML processing instruction."""
  1399. PREFIX: str = "<?"
  1400. SUFFIX: str = ">"
  1401. class XMLProcessingInstruction(ProcessingInstruction):
  1402. """An `XML processing instruction <https://www.w3.org/TR/REC-xml/#sec-pi>`_."""
  1403. PREFIX: str = "<?"
  1404. SUFFIX: str = "?>"
  1405. class Comment(PreformattedString):
  1406. """An `HTML comment <https://dev.w3.org/html5/spec-LC/syntax.html#comments>`_ or `XML comment <https://www.w3.org/TR/REC-xml/#sec-comments>`_."""
  1407. PREFIX: str = "<!--"
  1408. SUFFIX: str = "-->"
  1409. class Declaration(PreformattedString):
  1410. """An `XML declaration <https://www.w3.org/TR/REC-xml/#sec-prolog-dtd>`_."""
  1411. PREFIX: str = "<?"
  1412. SUFFIX: str = "?>"
  1413. class Doctype(PreformattedString):
  1414. """A `document type declaration <https://www.w3.org/TR/REC-xml/#dt-doctype>`_."""
  1415. @classmethod
  1416. def for_name_and_ids(
  1417. cls, name: str, pub_id: Optional[str], system_id: Optional[str]
  1418. ) -> Doctype:
  1419. """Generate an appropriate document type declaration for a given
  1420. public ID and system ID.
  1421. :param name: The name of the document's root element, e.g. 'html'.
  1422. :param pub_id: The Formal Public Identifier for this document type,
  1423. e.g. '-//W3C//DTD XHTML 1.1//EN'
  1424. :param system_id: The system identifier for this document type,
  1425. e.g. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
  1426. """
  1427. return Doctype(cls._string_for_name_and_ids(name, pub_id, system_id))
  1428. @classmethod
  1429. def _string_for_name_and_ids(
  1430. cls, name: str, pub_id: Optional[str], system_id: Optional[str]
  1431. ) -> str:
  1432. """Generate a string to be used as the basis of a Doctype object.
  1433. This is a separate method from for_name_and_ids() because the lxml
  1434. TreeBuilder needs to call it.
  1435. """
  1436. value = name or ""
  1437. if pub_id is not None:
  1438. value += ' PUBLIC "%s"' % pub_id
  1439. if system_id is not None:
  1440. value += ' "%s"' % system_id
  1441. elif system_id is not None:
  1442. value += ' SYSTEM "%s"' % system_id
  1443. return value
  1444. PREFIX: str = "<!DOCTYPE "
  1445. SUFFIX: str = ">\n"
  1446. class Stylesheet(NavigableString):
  1447. """A `NavigableString` representing the contents of a `<style> HTML
  1448. tag <https://dev.w3.org/html5/spec-LC/Overview.html#the-style-element>`_
  1449. (probably CSS).
  1450. Used to distinguish embedded stylesheets from textual content.
  1451. """
  1452. class Script(NavigableString):
  1453. """A `NavigableString` representing the contents of a `<script>
  1454. HTML tag
  1455. <https://dev.w3.org/html5/spec-LC/Overview.html#the-script-element>`_
  1456. (probably Javascript).
  1457. Used to distinguish executable code from textual content.
  1458. """
  1459. class TemplateString(NavigableString):
  1460. """A `NavigableString` representing a string found inside an `HTML
  1461. <template> tag <https://html.spec.whatwg.org/multipage/scripting.html#the-template-element>`_
  1462. embedded in a larger document.
  1463. Used to distinguish such strings from the main body of the document.
  1464. """
  1465. class RubyTextString(NavigableString):
  1466. """A NavigableString representing the contents of an `<rt> HTML
  1467. tag <https://dev.w3.org/html5/spec-LC/text-level-semantics.html#the-rt-element>`_.
  1468. Can be used to distinguish such strings from the strings they're
  1469. annotating.
  1470. """
  1471. class RubyParenthesisString(NavigableString):
  1472. """A NavigableString representing the contents of an `<rp> HTML
  1473. tag <https://dev.w3.org/html5/spec-LC/text-level-semantics.html#the-rp-element>`_.
  1474. """
  1475. class Tag(PageElement):
  1476. """An HTML or XML tag that is part of a parse tree, along with its
  1477. attributes, contents, and relationships to other parts of the tree.
  1478. When Beautiful Soup parses the markup ``<b>penguin</b>``, it will
  1479. create a `Tag` object representing the ``<b>`` tag. You can
  1480. instantiate `Tag` objects directly, but it's not necessary unless
  1481. you're adding entirely new markup to a parsed document. Most of
  1482. the constructor arguments are intended for use by the `TreeBuilder`
  1483. that's parsing a document.
  1484. :param parser: A `BeautifulSoup` object representing the parse tree this
  1485. `Tag` will be part of.
  1486. :param builder: The `TreeBuilder` being used to build the tree.
  1487. :param name: The name of the tag.
  1488. :param namespace: The URI of this tag's XML namespace, if any.
  1489. :param prefix: The prefix for this tag's XML namespace, if any.
  1490. :param attrs: A dictionary of attribute values.
  1491. :param parent: The `Tag` to use as the parent of this `Tag`. May be
  1492. the `BeautifulSoup` object itself.
  1493. :param previous: The `PageElement` that was parsed immediately before
  1494. parsing this tag.
  1495. :param is_xml: If True, this is an XML tag. Otherwise, this is an
  1496. HTML tag.
  1497. :param sourceline: The line number where this tag was found in its
  1498. source document.
  1499. :param sourcepos: The character position within ``sourceline`` where this
  1500. tag was found.
  1501. :param can_be_empty_element: If True, this tag should be
  1502. represented as <tag/>. If False, this tag should be represented
  1503. as <tag></tag>.
  1504. :param cdata_list_attributes: A dictionary of attributes whose values should
  1505. be parsed as lists of strings if they ever show up on this tag.
  1506. :param preserve_whitespace_tags: Names of tags whose contents
  1507. should have their whitespace preserved if they are encountered inside
  1508. this tag.
  1509. :param interesting_string_types: When iterating over this tag's
  1510. string contents in methods like `Tag.strings` or
  1511. `PageElement.get_text`, these are the types of strings that are
  1512. interesting enough to be considered. By default,
  1513. `NavigableString` (normal strings) and `CData` (CDATA
  1514. sections) are the only interesting string subtypes.
  1515. :param namespaces: A dictionary mapping currently active
  1516. namespace prefixes to URIs, as of the point in the parsing process when
  1517. this tag was encountered. This can be used later to
  1518. construct CSS selectors.
  1519. """
  1520. def __init__(
  1521. self,
  1522. parser: Optional[BeautifulSoup] = None,
  1523. builder: Optional[TreeBuilder] = None,
  1524. name: Optional[str] = None,
  1525. namespace: Optional[str] = None,
  1526. prefix: Optional[str] = None,
  1527. attrs: Optional[_RawOrProcessedAttributeValues] = None,
  1528. parent: Optional[Union[BeautifulSoup, Tag]] = None,
  1529. previous: _AtMostOneElement = None,
  1530. is_xml: Optional[bool] = None,
  1531. sourceline: Optional[int] = None,
  1532. sourcepos: Optional[int] = None,
  1533. can_be_empty_element: Optional[bool] = None,
  1534. cdata_list_attributes: Optional[Dict[str, Set[str]]] = None,
  1535. preserve_whitespace_tags: Optional[Set[str]] = None,
  1536. interesting_string_types: Optional[Set[Type[NavigableString]]] = None,
  1537. namespaces: Optional[Dict[str, str]] = None,
  1538. # NOTE: Any new arguments here need to be mirrored in
  1539. # Tag.copy_self, and potentially BeautifulSoup.new_tag
  1540. # as well.
  1541. ):
  1542. if parser is None:
  1543. self.parser_class = None
  1544. else:
  1545. # We don't actually store the parser object: that lets extracted
  1546. # chunks be garbage-collected.
  1547. self.parser_class = parser.__class__
  1548. if name is None:
  1549. raise ValueError("No value provided for new tag's name.")
  1550. self.name = name
  1551. self.namespace = namespace
  1552. self._namespaces = namespaces or {}
  1553. self.prefix = prefix
  1554. if (not builder or builder.store_line_numbers) and (
  1555. sourceline is not None or sourcepos is not None
  1556. ):
  1557. self.sourceline = sourceline
  1558. self.sourcepos = sourcepos
  1559. else:
  1560. self.sourceline = sourceline
  1561. self.sourcepos = sourcepos
  1562. attr_dict_class: type[AttributeDict]
  1563. attribute_value_list_class: type[AttributeValueList]
  1564. if builder is None:
  1565. if is_xml:
  1566. attr_dict_class = XMLAttributeDict
  1567. else:
  1568. attr_dict_class = HTMLAttributeDict
  1569. attribute_value_list_class = AttributeValueList
  1570. else:
  1571. attr_dict_class = builder.attribute_dict_class
  1572. attribute_value_list_class = builder.attribute_value_list_class
  1573. self.attribute_value_list_class = attribute_value_list_class
  1574. if attrs is None:
  1575. self.attrs = attr_dict_class()
  1576. else:
  1577. if builder is not None and builder.cdata_list_attributes:
  1578. self.attrs = builder._replace_cdata_list_attribute_values(
  1579. self.name, attrs
  1580. )
  1581. else:
  1582. self.attrs = attr_dict_class()
  1583. # Make sure that the values of any multi-valued
  1584. # attributes (e.g. when a Tag is copied) are stored in
  1585. # new lists.
  1586. for k, v in attrs.items():
  1587. if isinstance(v, list):
  1588. v = v.__class__(v)
  1589. self.attrs[k] = v
  1590. # If possible, determine ahead of time whether this tag is an
  1591. # XML tag.
  1592. if builder:
  1593. self.known_xml = builder.is_xml
  1594. else:
  1595. self.known_xml = is_xml
  1596. self.contents: List[PageElement] = []
  1597. self.setup(parent, previous)
  1598. self.hidden = False
  1599. if builder is None:
  1600. # In the absence of a TreeBuilder, use whatever values were
  1601. # passed in here. They're probably None, unless this is a copy of some
  1602. # other tag.
  1603. self.can_be_empty_element = can_be_empty_element
  1604. self.cdata_list_attributes = cdata_list_attributes
  1605. self.preserve_whitespace_tags = preserve_whitespace_tags
  1606. self.interesting_string_types = interesting_string_types
  1607. else:
  1608. # Set up any substitutions for this tag, such as the charset in a META tag.
  1609. self.attribute_value_list_class = builder.attribute_value_list_class
  1610. builder.set_up_substitutions(self)
  1611. # Ask the TreeBuilder whether this tag might be an empty-element tag.
  1612. self.can_be_empty_element = builder.can_be_empty_element(name)
  1613. # Keep track of the list of attributes of this tag that
  1614. # might need to be treated as a list.
  1615. #
  1616. # For performance reasons, we store the whole data structure
  1617. # rather than asking the question of every tag. Asking would
  1618. # require building a new data structure every time, and
  1619. # (unlike can_be_empty_element), we almost never need
  1620. # to check this.
  1621. self.cdata_list_attributes = builder.cdata_list_attributes
  1622. # Keep track of the names that might cause this tag to be treated as a
  1623. # whitespace-preserved tag.
  1624. self.preserve_whitespace_tags = builder.preserve_whitespace_tags
  1625. if self.name in builder.string_containers:
  1626. # This sort of tag uses a special string container
  1627. # subclass for most of its strings. We need to be able
  1628. # to look up the proper container subclass.
  1629. self.interesting_string_types = {builder.string_containers[self.name]}
  1630. else:
  1631. self.interesting_string_types = self.MAIN_CONTENT_STRING_TYPES
  1632. parser_class: Optional[type[BeautifulSoup]]
  1633. name: str
  1634. namespace: Optional[str]
  1635. prefix: Optional[str]
  1636. attrs: _AttributeValues
  1637. sourceline: Optional[int]
  1638. sourcepos: Optional[int]
  1639. known_xml: Optional[bool]
  1640. contents: List[PageElement]
  1641. hidden: bool
  1642. interesting_string_types: Optional[Set[Type[NavigableString]]]
  1643. can_be_empty_element: Optional[bool]
  1644. cdata_list_attributes: Optional[Dict[str, Set[str]]]
  1645. preserve_whitespace_tags: Optional[Set[str]]
  1646. #: :meta private:
  1647. parserClass = _deprecated_alias("parserClass", "parser_class", "4.0.0")
  1648. def __deepcopy__(self, memo: Dict[Any, Any], recursive: bool = True) -> Self:
  1649. """A deepcopy of a Tag is a new Tag, unconnected to the parse tree.
  1650. Its contents are a copy of the old Tag's contents.
  1651. """
  1652. clone = self.copy_self()
  1653. if recursive:
  1654. # Clone this tag's descendants recursively, but without
  1655. # making any recursive function calls.
  1656. tag_stack: List[Tag] = [clone]
  1657. for event, element in self._event_stream(self.descendants):
  1658. if event is Tag.END_ELEMENT_EVENT:
  1659. # Stop appending incoming Tags to the Tag that was
  1660. # just closed.
  1661. tag_stack.pop()
  1662. else:
  1663. descendant_clone = element.__deepcopy__(memo, recursive=False)
  1664. # Add to its parent's .contents
  1665. tag_stack[-1].append(descendant_clone)
  1666. if event is Tag.START_ELEMENT_EVENT:
  1667. # Add the Tag itself to the stack so that its
  1668. # children will be .appended to it.
  1669. tag_stack.append(cast(Tag, descendant_clone))
  1670. return clone
  1671. def copy_self(self) -> Self:
  1672. """Create a new Tag just like this one, but with no
  1673. contents and unattached to any parse tree.
  1674. This is the first step in the deepcopy process, but you can
  1675. call it on its own to create a copy of a Tag without copying its
  1676. contents.
  1677. """
  1678. clone = type(self)(
  1679. None,
  1680. None,
  1681. self.name,
  1682. self.namespace,
  1683. self.prefix,
  1684. self.attrs,
  1685. is_xml=self._is_xml,
  1686. sourceline=self.sourceline,
  1687. sourcepos=self.sourcepos,
  1688. can_be_empty_element=self.can_be_empty_element,
  1689. cdata_list_attributes=self.cdata_list_attributes,
  1690. preserve_whitespace_tags=self.preserve_whitespace_tags,
  1691. interesting_string_types=self.interesting_string_types,
  1692. namespaces=self._namespaces,
  1693. )
  1694. for attr in ("can_be_empty_element", "hidden"):
  1695. setattr(clone, attr, getattr(self, attr))
  1696. return clone
  1697. @property
  1698. def is_empty_element(self) -> bool:
  1699. """Is this tag an empty-element tag? (aka a self-closing tag)
  1700. A tag that has contents is never an empty-element tag.
  1701. A tag that has no contents may or may not be an empty-element
  1702. tag. It depends on the `TreeBuilder` used to create the
  1703. tag. If the builder has a designated list of empty-element
  1704. tags, then only a tag whose name shows up in that list is
  1705. considered an empty-element tag. This is usually the case
  1706. for HTML documents.
  1707. If the builder has no designated list of empty-element, then
  1708. any tag with no contents is an empty-element tag. This is usually
  1709. the case for XML documents.
  1710. """
  1711. return len(self.contents) == 0 and self.can_be_empty_element is True
  1712. @_deprecated("is_empty_element", "4.0.0")
  1713. def isSelfClosing(self) -> bool:
  1714. ": :meta private:"
  1715. return self.is_empty_element
  1716. @property
  1717. def string(self) -> Optional[str]:
  1718. """Convenience property to get the single string within this
  1719. `Tag`, assuming there is just one.
  1720. :return: If this `Tag` has a single child that's a
  1721. `NavigableString`, the return value is that string. If this
  1722. element has one child `Tag`, the return value is that child's
  1723. `Tag.string`, recursively. If this `Tag` has no children,
  1724. or has more than one child, the return value is ``None``.
  1725. If this property is unexpectedly returning ``None`` for you,
  1726. it's probably because your `Tag` has more than one thing
  1727. inside it.
  1728. """
  1729. if len(self.contents) != 1:
  1730. return None
  1731. child = self.contents[0]
  1732. if isinstance(child, NavigableString):
  1733. return child
  1734. elif isinstance(child, Tag):
  1735. return child.string
  1736. return None
  1737. @string.setter
  1738. def string(self, string: str) -> None:
  1739. """Replace the `Tag.contents` of this `Tag` with a single string."""
  1740. self.clear()
  1741. if isinstance(string, NavigableString):
  1742. new_class = string.__class__
  1743. else:
  1744. new_class = NavigableString
  1745. self.append(new_class(string))
  1746. #: :meta private:
  1747. MAIN_CONTENT_STRING_TYPES = {NavigableString, CData}
  1748. def _all_strings(
  1749. self, strip: bool = False, types: _OneOrMoreStringTypes = PageElement.default
  1750. ) -> Iterator[str]:
  1751. """Yield all strings of certain classes, possibly stripping them.
  1752. :param strip: If True, all strings will be stripped before being
  1753. yielded.
  1754. :param types: A tuple of NavigableString subclasses. Any strings of
  1755. a subclass not found in this list will be ignored. By
  1756. default, the subclasses considered are the ones found in
  1757. self.interesting_string_types. If that's not specified,
  1758. only NavigableString and CData objects will be
  1759. considered. That means no comments, processing
  1760. instructions, etc.
  1761. """
  1762. if types is self.default:
  1763. if self.interesting_string_types is None:
  1764. types = self.MAIN_CONTENT_STRING_TYPES
  1765. else:
  1766. types = self.interesting_string_types
  1767. for descendant in self.descendants:
  1768. if not isinstance(descendant, NavigableString):
  1769. continue
  1770. descendant_type = type(descendant)
  1771. if isinstance(types, type):
  1772. if descendant_type is not types:
  1773. # We're not interested in strings of this type.
  1774. continue
  1775. elif types is not None and descendant_type not in types:
  1776. # We're not interested in strings of this type.
  1777. continue
  1778. if strip:
  1779. stripped = descendant.strip()
  1780. if len(stripped) == 0:
  1781. continue
  1782. yield stripped
  1783. else:
  1784. yield descendant
  1785. strings = property(_all_strings)
  1786. def insert(self, position: int, *new_children: _InsertableElement) -> List[PageElement]:
  1787. """Insert one or more new PageElements as a child of this `Tag`.
  1788. This works similarly to :py:meth:`list.insert`, except you can insert
  1789. multiple elements at once.
  1790. :param position: The numeric position that should be occupied
  1791. in this Tag's `Tag.children` by the first new `PageElement`.
  1792. :param new_children: The PageElements to insert.
  1793. :return The newly inserted PageElements.
  1794. """
  1795. inserted: List[PageElement] = []
  1796. for new_child in new_children:
  1797. inserted.extend(self._insert(position, new_child))
  1798. position += 1
  1799. return inserted
  1800. def _insert(self, position: int, new_child: _InsertableElement) -> List[PageElement]:
  1801. if new_child is None:
  1802. raise ValueError("Cannot insert None into a tag.")
  1803. if new_child is self:
  1804. raise ValueError("Cannot insert a tag into itself.")
  1805. if isinstance(new_child, str) and not isinstance(new_child, NavigableString):
  1806. new_child = NavigableString(new_child)
  1807. from bs4 import BeautifulSoup
  1808. if isinstance(new_child, BeautifulSoup):
  1809. # We don't want to end up with a situation where one BeautifulSoup
  1810. # object contains another. Insert the BeautifulSoup's children and
  1811. # return them.
  1812. return self.insert(position, *list(new_child.contents))
  1813. position = min(position, len(self.contents))
  1814. if hasattr(new_child, "parent") and new_child.parent is not None:
  1815. # We're 'inserting' an element that's already one
  1816. # of this object's children.
  1817. if new_child.parent is self:
  1818. current_index = self.index(new_child)
  1819. if current_index < position:
  1820. # We're moving this element further down the list
  1821. # of this object's children. That means that when
  1822. # we extract this element, our target index will
  1823. # jump down one.
  1824. position -= 1
  1825. elif current_index == position:
  1826. # We're 'inserting' an element into its current location.
  1827. # This is a no-op.
  1828. return [new_child]
  1829. new_child.extract()
  1830. new_child.parent = self
  1831. previous_child = None
  1832. if position == 0:
  1833. new_child.previous_sibling = None
  1834. new_child.previous_element = self
  1835. else:
  1836. previous_child = self.contents[position - 1]
  1837. new_child.previous_sibling = previous_child
  1838. new_child.previous_sibling.next_sibling = new_child
  1839. new_child.previous_element = previous_child._last_descendant(False)
  1840. if new_child.previous_element is not None:
  1841. new_child.previous_element.next_element = new_child
  1842. new_childs_last_element = new_child._last_descendant(
  1843. is_initialized=False, accept_self=True
  1844. )
  1845. # new_childs_last_element can't be None because we passed
  1846. # accept_self=True into _last_descendant. Worst case,
  1847. # new_childs_last_element will be new_child itself. Making
  1848. # this cast removes several mypy complaints later on as we
  1849. # manipulate new_childs_last_element.
  1850. new_childs_last_element = cast(PageElement, new_childs_last_element)
  1851. if position >= len(self.contents):
  1852. new_child.next_sibling = None
  1853. parent: Optional[Tag] = self
  1854. parents_next_sibling = None
  1855. while parents_next_sibling is None and parent is not None:
  1856. parents_next_sibling = parent.next_sibling
  1857. parent = parent.parent
  1858. if parents_next_sibling is not None:
  1859. # We found the element that comes next in the document.
  1860. break
  1861. if parents_next_sibling is not None:
  1862. new_childs_last_element.next_element = parents_next_sibling
  1863. else:
  1864. # The last element of this tag is the last element in
  1865. # the document.
  1866. new_childs_last_element.next_element = None
  1867. else:
  1868. next_child = self.contents[position]
  1869. new_child.next_sibling = next_child
  1870. if new_child.next_sibling is not None:
  1871. new_child.next_sibling.previous_sibling = new_child
  1872. new_childs_last_element.next_element = next_child
  1873. if new_childs_last_element.next_element is not None:
  1874. new_childs_last_element.next_element.previous_element = (
  1875. new_childs_last_element
  1876. )
  1877. self.contents.insert(position, new_child)
  1878. return [new_child]
  1879. def unwrap(self) -> Self:
  1880. """Replace this `PageElement` with its contents.
  1881. :return: This object, no longer part of the tree.
  1882. """
  1883. my_parent = self.parent
  1884. if my_parent is None:
  1885. raise ValueError(
  1886. "Cannot replace an element with its contents when that "
  1887. "element is not part of a tree."
  1888. )
  1889. my_index = my_parent.index(self)
  1890. self.extract(_self_index=my_index)
  1891. for child in reversed(self.contents[:]):
  1892. my_parent.insert(my_index, child)
  1893. return self
  1894. replace_with_children = unwrap
  1895. @_deprecated("unwrap", "4.0.0")
  1896. def replaceWithChildren(self) -> _OneElement:
  1897. ": :meta private:"
  1898. return self.unwrap()
  1899. def append(self, tag: _InsertableElement) -> PageElement:
  1900. """
  1901. Appends the given `PageElement` to the contents of this `Tag`.
  1902. :param tag: A PageElement.
  1903. :return The newly appended PageElement.
  1904. """
  1905. return self.insert(len(self.contents), tag)[0]
  1906. def extend(self, tags: Union[Iterable[_InsertableElement], Tag]) -> List[PageElement]:
  1907. """Appends one or more objects to the contents of this
  1908. `Tag`.
  1909. :param tags: If a list of `PageElement` objects is provided,
  1910. they will be appended to this tag's contents, one at a time.
  1911. If a single `Tag` is provided, its `Tag.contents` will be
  1912. used to extend this object's `Tag.contents`.
  1913. :return The list of PageElements that were appended.
  1914. """
  1915. tag_list: Iterable[_InsertableElement]
  1916. if isinstance(tags, Tag):
  1917. tag_list = list(tags.contents)
  1918. elif isinstance(tags, (PageElement, str)):
  1919. # The caller should really be using append() instead,
  1920. # but we can make it work.
  1921. warnings.warn(
  1922. "A single non-Tag item was passed into Tag.extend. Use Tag.append instead.",
  1923. UserWarning,
  1924. stacklevel=2,
  1925. )
  1926. if isinstance(tags, str) and not isinstance(tags, PageElement):
  1927. tags = NavigableString(tags)
  1928. tag_list = [tags]
  1929. elif isinstance(tags, Iterable):
  1930. # Moving items around the tree may change their position in
  1931. # the original list. Make a list that won't change.
  1932. tag_list = list(tags)
  1933. results: List[PageElement] = []
  1934. for tag in tag_list:
  1935. results.append(self.append(tag))
  1936. return results
  1937. def clear(self, decompose: bool = False) -> None:
  1938. """Destroy all children of this `Tag` by calling
  1939. `PageElement.extract` on them.
  1940. :param decompose: If this is True, `PageElement.decompose` (a
  1941. more destructive method) will be called instead of
  1942. `PageElement.extract`.
  1943. """
  1944. for element in self.contents[:]:
  1945. if decompose:
  1946. element.decompose()
  1947. else:
  1948. element.extract()
  1949. def smooth(self) -> None:
  1950. """Smooth out the children of this `Tag` by consolidating consecutive
  1951. strings.
  1952. If you perform a lot of operations that modify the tree,
  1953. calling this method afterwards can make pretty-printed output
  1954. look more natural.
  1955. """
  1956. # Mark the first position of every pair of children that need
  1957. # to be consolidated. Do this rather than making a copy of
  1958. # self.contents, since in most cases very few strings will be
  1959. # affected.
  1960. marked = []
  1961. for i, a in enumerate(self.contents):
  1962. if isinstance(a, Tag):
  1963. # Recursively smooth children.
  1964. a.smooth()
  1965. if i == len(self.contents) - 1:
  1966. # This is the last item in .contents, and it's not a
  1967. # tag. There's no chance it needs any work.
  1968. continue
  1969. b = self.contents[i + 1]
  1970. if (
  1971. isinstance(a, NavigableString)
  1972. and isinstance(b, NavigableString)
  1973. and not isinstance(a, PreformattedString)
  1974. and not isinstance(b, PreformattedString)
  1975. ):
  1976. marked.append(i)
  1977. # Go over the marked positions in reverse order, so that
  1978. # removing items from .contents won't affect the remaining
  1979. # positions.
  1980. for i in reversed(marked):
  1981. a = cast(NavigableString, self.contents[i])
  1982. b = cast(NavigableString, self.contents[i + 1])
  1983. b.extract()
  1984. n = NavigableString(a + b)
  1985. a.replace_with(n)
  1986. def index(self, element: PageElement) -> int:
  1987. """Find the index of a child of this `Tag` (by identity, not value).
  1988. Doing this by identity avoids issues when a `Tag` contains two
  1989. children that have string equality.
  1990. :param element: Look for this `PageElement` in this object's contents.
  1991. """
  1992. for i, child in enumerate(self.contents):
  1993. if child is element:
  1994. return i
  1995. raise ValueError("Tag.index: element not in tag")
  1996. def get(
  1997. self, key: str, default: Optional[_AttributeValue] = None
  1998. ) -> Optional[_AttributeValue]:
  1999. """Returns the value of the 'key' attribute for the tag, or
  2000. the value given for 'default' if it doesn't have that
  2001. attribute.
  2002. :param key: The attribute to look for.
  2003. :param default: Use this value if the attribute is not present
  2004. on this `Tag`.
  2005. """
  2006. return self.attrs.get(key, default)
  2007. def get_attribute_list(
  2008. self, key: str, default: Optional[AttributeValueList] = None
  2009. ) -> AttributeValueList:
  2010. """The same as get(), but always returns a (possibly empty) list.
  2011. :param key: The attribute to look for.
  2012. :param default: Use this value if the attribute is not present
  2013. on this `Tag`.
  2014. :return: A list of strings, usually empty or containing only a single
  2015. value.
  2016. """
  2017. list_value: AttributeValueList
  2018. value = self.get(key, default)
  2019. if value is None:
  2020. list_value = self.attribute_value_list_class()
  2021. elif isinstance(value, list):
  2022. list_value = value
  2023. else:
  2024. if not isinstance(value, str):
  2025. value = cast(str, value)
  2026. list_value = self.attribute_value_list_class([value])
  2027. return list_value
  2028. def has_attr(self, key: str) -> bool:
  2029. """Does this `Tag` have an attribute with the given name?"""
  2030. return key in self.attrs
  2031. def __hash__(self) -> int:
  2032. return str(self).__hash__()
  2033. def __getitem__(self, key: str) -> _AttributeValue:
  2034. """tag[key] returns the value of the 'key' attribute for the Tag,
  2035. and throws an exception if it's not there."""
  2036. return self.attrs[key]
  2037. def __iter__(self) -> Iterator[PageElement]:
  2038. "Iterating over a Tag iterates over its contents."
  2039. return iter(self.contents)
  2040. def __len__(self) -> int:
  2041. "The length of a Tag is the length of its list of contents."
  2042. return len(self.contents)
  2043. def __contains__(self, x: Any) -> bool:
  2044. return x in self.contents
  2045. def __bool__(self) -> bool:
  2046. "A tag is non-None even if it has no contents."
  2047. return True
  2048. def __setitem__(self, key: str, value: _AttributeValue) -> None:
  2049. """Setting tag[key] sets the value of the 'key' attribute for the
  2050. tag."""
  2051. self.attrs[key] = value
  2052. def __delitem__(self, key: str) -> None:
  2053. "Deleting tag[key] deletes all 'key' attributes for the tag."
  2054. self.attrs.pop(key, None)
  2055. @overload
  2056. def __call__( # pyright: ignore [reportOverlappingOverload]
  2057. self,
  2058. name: _FindMethodName = None,
  2059. attrs: Optional[_StrainableAttributes] = None,
  2060. recursive: bool = True,
  2061. string: None = None,
  2062. limit: Optional[int] = None,
  2063. _stacklevel: int = 2,
  2064. **kwargs: _StrainableAttribute,
  2065. ) -> _SomeTags:
  2066. ...
  2067. @overload
  2068. def __call__(
  2069. self,
  2070. name: None = None,
  2071. attrs: None = None,
  2072. recursive: bool = True,
  2073. string: _StrainableString = "",
  2074. limit: Optional[int] = None,
  2075. _stacklevel: int = 2,
  2076. **kwargs: _StrainableAttribute,
  2077. ) -> _SomeNavigableStrings:
  2078. ...
  2079. def __call__(
  2080. self,
  2081. name: _FindMethodName = None,
  2082. attrs: Optional[_StrainableAttributes] = None,
  2083. recursive: bool = True,
  2084. string: Optional[_StrainableString] = None,
  2085. limit: Optional[int] = None,
  2086. _stacklevel: int = 2,
  2087. **kwargs: _StrainableAttribute,
  2088. ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]:
  2089. """Calling a Tag like a function is the same as calling its
  2090. find_all() method. Eg. tag('a') returns a list of all the A tags
  2091. found within this tag."""
  2092. if string is not None and (name is not None or attrs is not None or kwargs):
  2093. # TODO: Using the @overload decorator to express the three ways you
  2094. # could get into this path is way too much code for a rarely(?) used
  2095. # feature.
  2096. return cast(ResultSet[Tag], self.find_all(name, attrs, recursive, string, limit, _stacklevel, **kwargs)) #type: ignore
  2097. if string is None:
  2098. # If string is None, we're searching for tags.
  2099. tags:ResultSet[Tag] = self.find_all(
  2100. name, attrs, recursive, None, limit, _stacklevel, **kwargs
  2101. )
  2102. return tags
  2103. # Otherwise, we're searching for strings.
  2104. strings:ResultSet[NavigableString] = self.find_all(
  2105. None, None, recursive, string, limit, _stacklevel, **kwargs
  2106. )
  2107. return strings
  2108. def __getattr__(self, subtag: str) -> Optional[Tag]:
  2109. """Calling tag.subtag is the same as calling tag.find(name="subtag")"""
  2110. # print("Getattr %s.%s" % (self.__class__, tag))
  2111. result: _AtMostOneElement
  2112. if len(subtag) > 3 and subtag.endswith("Tag"):
  2113. # BS3: soup.aTag -> "soup.find("a")
  2114. tag_name = subtag[:-3]
  2115. warnings.warn(
  2116. '.%(name)sTag is deprecated, use .find("%(name)s") instead. If you really were looking for a tag called %(name)sTag, use .find("%(name)sTag")'
  2117. % dict(name=tag_name),
  2118. DeprecationWarning,
  2119. stacklevel=2,
  2120. )
  2121. result = self.find(tag_name)
  2122. # We special case contents to avoid recursion.
  2123. elif not subtag.startswith("__") and not subtag == "contents":
  2124. result = self.find(subtag)
  2125. else:
  2126. raise AttributeError(
  2127. "'%s' object has no attribute '%s'" % (self.__class__, subtag)
  2128. )
  2129. return result
  2130. def __eq__(self, other: Any) -> bool:
  2131. """Returns true iff this Tag has the same name, the same attributes,
  2132. and the same contents (recursively) as `other`."""
  2133. if self is other:
  2134. return True
  2135. if not isinstance(other, Tag):
  2136. return False
  2137. if (
  2138. not hasattr(other, "name")
  2139. or not hasattr(other, "attrs")
  2140. or not hasattr(other, "contents")
  2141. or self.name != other.name
  2142. or self.attrs != other.attrs
  2143. or len(self) != len(other)
  2144. ):
  2145. return False
  2146. for i, my_child in enumerate(self.contents):
  2147. if my_child != other.contents[i]:
  2148. return False
  2149. return True
  2150. def __ne__(self, other: Any) -> bool:
  2151. """Returns true iff this Tag is not identical to `other`,
  2152. as defined in __eq__."""
  2153. return not self == other
  2154. def __repr__(self) -> str:
  2155. """Renders this `Tag` as a string."""
  2156. return self.decode()
  2157. __str__ = __unicode__ = __repr__
  2158. def encode(
  2159. self,
  2160. encoding: _Encoding = DEFAULT_OUTPUT_ENCODING,
  2161. indent_level: Optional[int] = None,
  2162. formatter: _FormatterOrName = "minimal",
  2163. errors: str = "xmlcharrefreplace",
  2164. ) -> bytes:
  2165. """Render this `Tag` and its contents as a bytestring.
  2166. :param encoding: The encoding to use when converting to
  2167. a bytestring. This may also affect the text of the document,
  2168. specifically any encoding declarations within the document.
  2169. :param indent_level: Each line of the rendering will be
  2170. indented this many levels. (The ``formatter`` decides what a
  2171. 'level' means, in terms of spaces or other characters
  2172. output.) This is used internally in recursive calls while
  2173. pretty-printing.
  2174. :param formatter: Either a `Formatter` object, or a string naming one of
  2175. the standard formatters.
  2176. :param errors: An error handling strategy such as
  2177. 'xmlcharrefreplace'. This value is passed along into
  2178. :py:meth:`str.encode` and its value should be one of the `error
  2179. handling constants defined by Python's codecs module
  2180. <https://docs.python.org/3/library/codecs.html#error-handlers>`_.
  2181. """
  2182. # Turn the data structure into Unicode, then encode the
  2183. # Unicode.
  2184. u = self.decode(indent_level, encoding, formatter)
  2185. return u.encode(encoding, errors)
  2186. def decode(
  2187. self,
  2188. indent_level: Optional[int] = None,
  2189. eventual_encoding: _Encoding = DEFAULT_OUTPUT_ENCODING,
  2190. formatter: _FormatterOrName = "minimal",
  2191. iterator: Optional[Iterator[PageElement]] = None,
  2192. ) -> str:
  2193. """Render this `Tag` and its contents as a Unicode string.
  2194. :param indent_level: Each line of the rendering will be
  2195. indented this many levels. (The ``formatter`` decides what a
  2196. 'level' means, in terms of spaces or other characters
  2197. output.) This is used internally in recursive calls while
  2198. pretty-printing.
  2199. :param encoding: The encoding you intend to use when
  2200. converting the string to a bytestring. decode() is *not*
  2201. responsible for performing that encoding. This information
  2202. is needed so that a real encoding can be substituted in if
  2203. the document contains an encoding declaration (e.g. in a
  2204. <meta> tag).
  2205. :param formatter: Either a `Formatter` object, or a string
  2206. naming one of the standard formatters.
  2207. :param iterator: The iterator to use when navigating over the
  2208. parse tree. This is only used by `Tag.decode_contents` and
  2209. you probably won't need to use it.
  2210. """
  2211. pieces = []
  2212. # First off, turn a non-Formatter `formatter` into a Formatter
  2213. # object. This will stop the lookup from happening over and
  2214. # over again.
  2215. if not isinstance(formatter, Formatter):
  2216. formatter = self.formatter_for_name(formatter)
  2217. if indent_level is True:
  2218. indent_level = 0
  2219. # The currently active tag that put us into string literal
  2220. # mode. Until this element is closed, children will be treated
  2221. # as string literals and not pretty-printed. String literal
  2222. # mode is turned on immediately after this tag begins, and
  2223. # turned off immediately before it's closed. This means there
  2224. # will be whitespace before and after the tag itself.
  2225. string_literal_tag = None
  2226. for event, element in self._event_stream(iterator):
  2227. if event in (Tag.START_ELEMENT_EVENT, Tag.EMPTY_ELEMENT_EVENT):
  2228. element = cast(Tag, element)
  2229. piece = element._format_tag(eventual_encoding, formatter, opening=True)
  2230. elif event is Tag.END_ELEMENT_EVENT:
  2231. element = cast(Tag, element)
  2232. piece = element._format_tag(eventual_encoding, formatter, opening=False)
  2233. if indent_level is not None:
  2234. indent_level -= 1
  2235. else:
  2236. element = cast(NavigableString, element)
  2237. piece = element.output_ready(formatter)
  2238. # Now we need to apply the 'prettiness' -- extra
  2239. # whitespace before and/or after this tag. This can get
  2240. # complicated because certain tags, like <pre> and
  2241. # <script>, can't be prettified, since adding whitespace would
  2242. # change the meaning of the content.
  2243. # The default behavior is to add whitespace before and
  2244. # after an element when string literal mode is off, and to
  2245. # leave things as they are when string literal mode is on.
  2246. if string_literal_tag:
  2247. indent_before = indent_after = False
  2248. else:
  2249. indent_before = indent_after = True
  2250. # The only time the behavior is more complex than that is
  2251. # when we encounter an opening or closing tag that might
  2252. # put us into or out of string literal mode.
  2253. if (
  2254. event is Tag.START_ELEMENT_EVENT
  2255. and not string_literal_tag
  2256. and not cast(Tag, element)._should_pretty_print()
  2257. ):
  2258. # We are about to enter string literal mode. Add
  2259. # whitespace before this tag, but not after. We
  2260. # will stay in string literal mode until this tag
  2261. # is closed.
  2262. indent_before = True
  2263. indent_after = False
  2264. string_literal_tag = element
  2265. elif event is Tag.END_ELEMENT_EVENT and element is string_literal_tag:
  2266. # We are about to exit string literal mode by closing
  2267. # the tag that sent us into that mode. Add whitespace
  2268. # after this tag, but not before.
  2269. indent_before = False
  2270. indent_after = True
  2271. string_literal_tag = None
  2272. # Now we know whether to add whitespace before and/or
  2273. # after this element.
  2274. if indent_level is not None:
  2275. if indent_before or indent_after:
  2276. if isinstance(element, NavigableString):
  2277. piece = piece.strip()
  2278. if piece:
  2279. piece = self._indent_string(
  2280. piece, indent_level, formatter, indent_before, indent_after
  2281. )
  2282. if event == Tag.START_ELEMENT_EVENT:
  2283. indent_level += 1
  2284. pieces.append(piece)
  2285. return "".join(pieces)
  2286. class _TreeTraversalEvent(object):
  2287. """An internal class representing an event in the process
  2288. of traversing a parse tree.
  2289. :meta private:
  2290. """
  2291. # Stand-ins for the different events yielded by _event_stream
  2292. START_ELEMENT_EVENT = _TreeTraversalEvent() #: :meta private:
  2293. END_ELEMENT_EVENT = _TreeTraversalEvent() #: :meta private:
  2294. EMPTY_ELEMENT_EVENT = _TreeTraversalEvent() #: :meta private:
  2295. STRING_ELEMENT_EVENT = _TreeTraversalEvent() #: :meta private:
  2296. def _event_stream(
  2297. self, iterator: Optional[Iterator[PageElement]] = None
  2298. ) -> Iterator[Tuple[_TreeTraversalEvent, PageElement]]:
  2299. """Yield a sequence of events that can be used to reconstruct the DOM
  2300. for this element.
  2301. This lets us recreate the nested structure of this element
  2302. (e.g. when formatting it as a string) without using recursive
  2303. method calls.
  2304. This is similar in concept to the SAX API, but it's a simpler
  2305. interface designed for internal use. The events are different
  2306. from SAX and the arguments associated with the events are Tags
  2307. and other Beautiful Soup objects.
  2308. :param iterator: An alternate iterator to use when traversing
  2309. the tree.
  2310. """
  2311. tag_stack: List[Tag] = []
  2312. iterator = iterator or self.self_and_descendants
  2313. for c in iterator:
  2314. # If the parent of the element we're about to yield is not
  2315. # the tag currently on the stack, it means that the tag on
  2316. # the stack closed before this element appeared.
  2317. while tag_stack and c.parent != tag_stack[-1]:
  2318. now_closed_tag = tag_stack.pop()
  2319. yield Tag.END_ELEMENT_EVENT, now_closed_tag
  2320. if isinstance(c, Tag):
  2321. if c.is_empty_element:
  2322. yield Tag.EMPTY_ELEMENT_EVENT, c
  2323. else:
  2324. yield Tag.START_ELEMENT_EVENT, c
  2325. tag_stack.append(c)
  2326. continue
  2327. else:
  2328. yield Tag.STRING_ELEMENT_EVENT, c
  2329. while tag_stack:
  2330. now_closed_tag = tag_stack.pop()
  2331. yield Tag.END_ELEMENT_EVENT, now_closed_tag
  2332. def _indent_string(
  2333. self,
  2334. s: str,
  2335. indent_level: int,
  2336. formatter: Formatter,
  2337. indent_before: bool,
  2338. indent_after: bool,
  2339. ) -> str:
  2340. """Add indentation whitespace before and/or after a string.
  2341. :param s: The string to amend with whitespace.
  2342. :param indent_level: The indentation level; affects how much
  2343. whitespace goes before the string.
  2344. :param indent_before: Whether or not to add whitespace
  2345. before the string.
  2346. :param indent_after: Whether or not to add whitespace
  2347. (a newline) after the string.
  2348. """
  2349. space_before = ""
  2350. if indent_before and indent_level:
  2351. space_before = formatter.indent * indent_level
  2352. space_after = ""
  2353. if indent_after:
  2354. space_after = "\n"
  2355. return space_before + s + space_after
  2356. def _format_tag(
  2357. self, eventual_encoding: str, formatter: Formatter, opening: bool
  2358. ) -> str:
  2359. if self.hidden:
  2360. # A hidden tag is invisible, although its contents
  2361. # are visible.
  2362. return ""
  2363. # A tag starts with the < character (see below).
  2364. # Then the / character, if this is a closing tag.
  2365. closing_slash = ""
  2366. if not opening:
  2367. closing_slash = "/"
  2368. # Then an optional namespace prefix.
  2369. prefix = ""
  2370. if self.prefix:
  2371. prefix = self.prefix + ":"
  2372. # Then a list of attribute values, if this is an opening tag.
  2373. attribute_string = ""
  2374. if opening:
  2375. attributes = formatter.attributes(self)
  2376. attrs = []
  2377. for key, val in attributes:
  2378. if val is None:
  2379. decoded = key
  2380. else:
  2381. if isinstance(val, list) or isinstance(val, tuple):
  2382. val = " ".join(val)
  2383. elif not isinstance(val, str):
  2384. val = str(val)
  2385. elif (
  2386. isinstance(val, AttributeValueWithCharsetSubstitution)
  2387. and eventual_encoding is not None
  2388. ):
  2389. val = val.substitute_encoding(eventual_encoding)
  2390. text = formatter.attribute_value(val)
  2391. decoded = str(key) + "=" + formatter.quoted_attribute_value(text)
  2392. attrs.append(decoded)
  2393. if attrs:
  2394. attribute_string = " " + " ".join(attrs)
  2395. # Then an optional closing slash (for a void element in an
  2396. # XML document).
  2397. void_element_closing_slash = ""
  2398. if self.is_empty_element:
  2399. void_element_closing_slash = formatter.void_element_close_prefix or ""
  2400. # Put it all together.
  2401. return (
  2402. "<"
  2403. + closing_slash
  2404. + prefix
  2405. + self.name
  2406. + attribute_string
  2407. + void_element_closing_slash
  2408. + ">"
  2409. )
  2410. def _should_pretty_print(self, indent_level: int = 1) -> bool:
  2411. """Should this tag be pretty-printed?
  2412. Most of them should, but some (such as <pre> in HTML
  2413. documents) should not.
  2414. """
  2415. return indent_level is not None and (
  2416. not self.preserve_whitespace_tags
  2417. or self.name not in self.preserve_whitespace_tags
  2418. )
  2419. @overload
  2420. def prettify(
  2421. self,
  2422. encoding: None = None,
  2423. formatter: _FormatterOrName = "minimal",
  2424. ) -> str:
  2425. ...
  2426. @overload
  2427. def prettify(
  2428. self,
  2429. encoding: _Encoding,
  2430. formatter: _FormatterOrName = "minimal",
  2431. ) -> bytes:
  2432. ...
  2433. def prettify(
  2434. self,
  2435. encoding: Optional[_Encoding] = None,
  2436. formatter: _FormatterOrName = "minimal",
  2437. ) -> Union[str, bytes]:
  2438. """Pretty-print this `Tag` as a string or bytestring.
  2439. :param encoding: The encoding of the bytestring, or None if you want Unicode.
  2440. :param formatter: A Formatter object, or a string naming one of
  2441. the standard formatters.
  2442. :return: A string (if no ``encoding`` is provided) or a bytestring
  2443. (otherwise).
  2444. """
  2445. if encoding is None:
  2446. return self.decode(indent_level=0, formatter=formatter)
  2447. else:
  2448. return self.encode(encoding=encoding, indent_level=0, formatter=formatter)
  2449. def decode_contents(
  2450. self,
  2451. indent_level: Optional[int] = None,
  2452. eventual_encoding: _Encoding = DEFAULT_OUTPUT_ENCODING,
  2453. formatter: _FormatterOrName = "minimal",
  2454. ) -> str:
  2455. """Renders the contents of this tag as a Unicode string.
  2456. :param indent_level: Each line of the rendering will be
  2457. indented this many levels. (The formatter decides what a
  2458. 'level' means in terms of spaces or other characters
  2459. output.) Used internally in recursive calls while
  2460. pretty-printing.
  2461. :param eventual_encoding: The tag is destined to be
  2462. encoded into this encoding. decode_contents() is *not*
  2463. responsible for performing that encoding. This information
  2464. is needed so that a real encoding can be substituted in if
  2465. the document contains an encoding declaration (e.g. in a
  2466. <meta> tag).
  2467. :param formatter: A `Formatter` object, or a string naming one of
  2468. the standard Formatters.
  2469. """
  2470. return self.decode(
  2471. indent_level, eventual_encoding, formatter, iterator=self.descendants
  2472. )
  2473. def encode_contents(
  2474. self,
  2475. indent_level: Optional[int] = None,
  2476. encoding: _Encoding = DEFAULT_OUTPUT_ENCODING,
  2477. formatter: _FormatterOrName = "minimal",
  2478. ) -> bytes:
  2479. """Renders the contents of this PageElement as a bytestring.
  2480. :param indent_level: Each line of the rendering will be
  2481. indented this many levels. (The ``formatter`` decides what a
  2482. 'level' means, in terms of spaces or other characters
  2483. output.) This is used internally in recursive calls while
  2484. pretty-printing.
  2485. :param formatter: Either a `Formatter` object, or a string naming one of
  2486. the standard formatters.
  2487. :param encoding: The bytestring will be in this encoding.
  2488. """
  2489. contents = self.decode_contents(indent_level, encoding, formatter)
  2490. return contents.encode(encoding)
  2491. @_deprecated("encode_contents", "4.0.0")
  2492. def renderContents(
  2493. self,
  2494. encoding: _Encoding = DEFAULT_OUTPUT_ENCODING,
  2495. prettyPrint: bool = False,
  2496. indentLevel: Optional[int] = 0,
  2497. ) -> bytes:
  2498. """Deprecated method for BS3 compatibility.
  2499. :meta private:
  2500. """
  2501. if not prettyPrint:
  2502. indentLevel = None
  2503. return self.encode_contents(indent_level=indentLevel, encoding=encoding)
  2504. # Soup methods
  2505. @overload
  2506. def find(
  2507. self,
  2508. name: _FindMethodName = None,
  2509. attrs: Optional[_StrainableAttributes] = None,
  2510. recursive: bool = True,
  2511. string: None=None,
  2512. **kwargs: _StrainableAttribute,
  2513. ) -> _AtMostOneTag:
  2514. ...
  2515. @overload
  2516. def find(
  2517. self,
  2518. name: None=None,
  2519. attrs: None=None,
  2520. recursive: bool = True,
  2521. string: _StrainableString="",
  2522. ) -> _AtMostOneNavigableString:
  2523. ...
  2524. def find(
  2525. self,
  2526. name: _FindMethodName = None,
  2527. attrs: Optional[_StrainableAttributes] = None,
  2528. recursive: bool = True,
  2529. string: Optional[_StrainableString] = None,
  2530. **kwargs: _StrainableAttribute,
  2531. ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]:
  2532. """Look in the children of this PageElement and find the first
  2533. PageElement that matches the given criteria.
  2534. All find_* methods take a common set of arguments. See the online
  2535. documentation for detailed explanations.
  2536. :param name: A filter on tag name.
  2537. :param attrs: Additional filters on attribute values.
  2538. :param recursive: If this is True, find() will perform a
  2539. recursive search of this Tag's children. Otherwise,
  2540. only the direct children will be considered.
  2541. :param string: A filter on the `Tag.string` attribute.
  2542. :kwargs: Additional filters on attribute values.
  2543. """
  2544. if string is not None and (name is not None or attrs is not None or kwargs):
  2545. # TODO: Using the @overload decorator to express the three ways you
  2546. # could get into this path is way too much code for a rarely(?) used
  2547. # feature.
  2548. elements = self.find_all(name, attrs, recursive, string, 1, _stacklevel=3, **kwargs) # type:ignore
  2549. if elements:
  2550. return cast(Tag, elements[0])
  2551. elif string is None:
  2552. tags = self.find_all(name, attrs, recursive, None, 1, _stacklevel=3, **kwargs)
  2553. if tags:
  2554. return cast(Tag, tags[0])
  2555. else:
  2556. strings = self.find_all(None, None, recursive, string, 1, _stacklevel=3, **kwargs)
  2557. if strings:
  2558. return cast(NavigableString, strings[0])
  2559. return None
  2560. findChild = _deprecated_function_alias("findChild", "find", "3.0.0")
  2561. @overload
  2562. def find_all( # pyright: ignore [reportOverlappingOverload]
  2563. self,
  2564. name: _FindMethodName = None,
  2565. attrs: Optional[_StrainableAttributes] = None,
  2566. recursive: bool = True,
  2567. string: None = None,
  2568. limit: Optional[int] = None,
  2569. _stacklevel: int = 2,
  2570. **kwargs: _StrainableAttribute,
  2571. ) -> _SomeTags:
  2572. ...
  2573. @overload
  2574. def find_all(
  2575. self,
  2576. name: None = None,
  2577. attrs: None = None,
  2578. recursive: bool = True,
  2579. string: _StrainableString = "",
  2580. limit: Optional[int] = None,
  2581. _stacklevel: int = 2,
  2582. **kwargs: _StrainableAttribute,
  2583. ) -> _SomeNavigableStrings:
  2584. ...
  2585. def find_all(
  2586. self,
  2587. name: _FindMethodName = None,
  2588. attrs: Optional[_StrainableAttributes] = None,
  2589. recursive: bool = True,
  2590. string: Optional[_StrainableString] = None,
  2591. limit: Optional[int] = None,
  2592. _stacklevel: int = 2,
  2593. **kwargs: _StrainableAttribute,
  2594. ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]:
  2595. """Look in the children of this `PageElement` and find all
  2596. `PageElement` objects that match the given criteria.
  2597. All find_* methods take a common set of arguments. See the online
  2598. documentation for detailed explanations.
  2599. :param name: A filter on tag name.
  2600. :param attrs: Additional filters on attribute values.
  2601. :param recursive: If this is True, find_all() will perform a
  2602. recursive search of this PageElement's children. Otherwise,
  2603. only the direct children will be considered.
  2604. :param limit: Stop looking after finding this many results.
  2605. :param _stacklevel: Used internally to improve warning messages.
  2606. :kwargs: Additional filters on attribute values.
  2607. """
  2608. generator = self.descendants
  2609. if not recursive:
  2610. generator = self.children
  2611. _stacklevel += 1
  2612. if string is not None and (name is not None or attrs is not None or kwargs):
  2613. # TODO: Using the @overload decorator to express the three ways you
  2614. # could get into this path is way too much code for a rarely(?) used
  2615. # feature.
  2616. return cast(ResultSet[Tag],
  2617. self._find_all(name, attrs, string, limit, generator,
  2618. _stacklevel=_stacklevel, **kwargs)
  2619. )
  2620. if string is None:
  2621. # If string is None, we're searching for tags.
  2622. return cast(ResultSet[Tag], self._find_all(
  2623. name, attrs, None, limit, generator, _stacklevel=_stacklevel, **kwargs
  2624. ))
  2625. # Otherwise, we're searching for strings.
  2626. return cast(ResultSet[NavigableString], self._find_all(
  2627. None, None, string, limit, generator, _stacklevel=_stacklevel, **kwargs
  2628. ))
  2629. findAll = _deprecated_function_alias("findAll", "find_all", "4.0.0")
  2630. findChildren = _deprecated_function_alias("findChildren", "find_all", "3.0.0")
  2631. # Generator methods
  2632. @property
  2633. def children(self) -> Iterator[PageElement]:
  2634. """Iterate over all direct children of this `PageElement`."""
  2635. return (x for x in self.contents)
  2636. @property
  2637. def self_and_descendants(self) -> Iterator[PageElement]:
  2638. """Iterate over this `Tag` and its children in a
  2639. breadth-first sequence.
  2640. """
  2641. return self._self_and(self.descendants)
  2642. @property
  2643. def descendants(self) -> Iterator[PageElement]:
  2644. """Iterate over all children of this `Tag` in a
  2645. breadth-first sequence.
  2646. """
  2647. if not len(self.contents):
  2648. return
  2649. # _last_descendant() can't return None here because
  2650. # accept_self is True. Worst case, last_descendant will end up
  2651. # as self.
  2652. last_descendant = cast(PageElement, self._last_descendant(accept_self=True))
  2653. stopNode = last_descendant.next_element
  2654. current: _AtMostOneElement = self.contents[0]
  2655. while current is not stopNode and current is not None:
  2656. successor = current.next_element
  2657. yield current
  2658. current = successor
  2659. # CSS selector code
  2660. def select_one(
  2661. self, selector: str, namespaces: Optional[Dict[str, str]] = None, **kwargs: Any
  2662. ) -> Optional[Tag]:
  2663. """Perform a CSS selection operation on the current element.
  2664. :param selector: A CSS selector.
  2665. :param namespaces: A dictionary mapping namespace prefixes
  2666. used in the CSS selector to namespace URIs. By default,
  2667. Beautiful Soup will use the prefixes it encountered while
  2668. parsing the document.
  2669. :param kwargs: Keyword arguments to be passed into Soup Sieve's
  2670. soupsieve.select() method.
  2671. """
  2672. return self.css.select_one(selector, namespaces, **kwargs)
  2673. def select(
  2674. self,
  2675. selector: str,
  2676. namespaces: Optional[Dict[str, str]] = None,
  2677. limit: int = 0,
  2678. **kwargs: Any,
  2679. ) -> ResultSet[Tag]:
  2680. """Perform a CSS selection operation on the current element.
  2681. This uses the SoupSieve library.
  2682. :param selector: A string containing a CSS selector.
  2683. :param namespaces: A dictionary mapping namespace prefixes
  2684. used in the CSS selector to namespace URIs. By default,
  2685. Beautiful Soup will use the prefixes it encountered while
  2686. parsing the document.
  2687. :param limit: After finding this number of results, stop looking.
  2688. :param kwargs: Keyword arguments to be passed into SoupSieve's
  2689. soupsieve.select() method.
  2690. """
  2691. return self.css.select(selector, namespaces, limit, **kwargs)
  2692. @property
  2693. def css(self) -> CSS:
  2694. """Return an interface to the CSS selector API."""
  2695. return CSS(self)
  2696. # Old names for backwards compatibility
  2697. @_deprecated("children", "4.0.0")
  2698. def childGenerator(self) -> Iterator[PageElement]:
  2699. """Deprecated generator.
  2700. :meta private:
  2701. """
  2702. return self.children
  2703. @_deprecated("descendants", "4.0.0")
  2704. def recursiveChildGenerator(self) -> Iterator[PageElement]:
  2705. """Deprecated generator.
  2706. :meta private:
  2707. """
  2708. return self.descendants
  2709. @_deprecated("has_attr", "4.0.0")
  2710. def has_key(self, key: str) -> bool:
  2711. """Deprecated method. This was kind of misleading because has_key()
  2712. (attributes) was different from __in__ (contents).
  2713. has_key() is gone in Python 3, anyway.
  2714. :meta private:
  2715. """
  2716. return self.has_attr(key)
  2717. _PageElementT = TypeVar("_PageElementT", bound=PageElement)
  2718. class ResultSet(List[_PageElementT], Generic[_PageElementT]):
  2719. """A ResultSet is a list of `PageElement` objects, gathered as the result
  2720. of matching an :py:class:`ElementFilter` against a parse tree. Basically, a list of
  2721. search results.
  2722. """
  2723. source: Optional[ElementFilter]
  2724. def __init__(
  2725. self, source: Optional[ElementFilter], result: Iterable[_PageElementT] = ()
  2726. ) -> None:
  2727. super(ResultSet, self).__init__(result)
  2728. self.source = source
  2729. def __getattr__(self, key: str) -> None:
  2730. """Raise a helpful exception to explain a common code fix."""
  2731. raise AttributeError(
  2732. f"""ResultSet object has no attribute "{key}". You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?"""
  2733. )
  2734. # Now that all the classes used by SoupStrainer have been defined,
  2735. # import SoupStrainer itself into this module to preserve the
  2736. # backwards compatibility of anyone who imports
  2737. # bs4.element.SoupStrainer.
  2738. from bs4.filter import SoupStrainer # noqa: E402