__init__.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. """Beautiful Soup Elixir and Tonic - "The Screen-Scraper's Friend".
  2. http://www.crummy.com/software/BeautifulSoup/
  3. Beautiful Soup uses a pluggable XML or HTML parser to parse a
  4. (possibly invalid) document into a tree representation. Beautiful Soup
  5. provides methods and Pythonic idioms that make it easy to navigate,
  6. search, and modify the parse tree.
  7. Beautiful Soup works with Python 3.7 and up. It works better if lxml
  8. and/or html5lib is installed, but they are not required.
  9. For more than you ever wanted to know about Beautiful Soup, see the
  10. documentation: http://www.crummy.com/software/BeautifulSoup/bs4/doc/
  11. """
  12. __author__ = "Leonard Richardson (leonardr@segfault.org)"
  13. __version__ = "4.14.3"
  14. __copyright__ = "Copyright (c) 2004-2025 Leonard Richardson"
  15. # Use of this source code is governed by the MIT license.
  16. __license__ = "MIT"
  17. __all__ = [
  18. "AttributeResemblesVariableWarning",
  19. "BeautifulSoup",
  20. "Comment",
  21. "Declaration",
  22. "ProcessingInstruction",
  23. "ResultSet",
  24. "CSS",
  25. "Script",
  26. "Stylesheet",
  27. "Tag",
  28. "TemplateString",
  29. "ElementFilter",
  30. "UnicodeDammit",
  31. "CData",
  32. "Doctype",
  33. # Exceptions
  34. "FeatureNotFound",
  35. "ParserRejectedMarkup",
  36. "StopParsing",
  37. # Warnings
  38. "AttributeResemblesVariableWarning",
  39. "GuessedAtParserWarning",
  40. "MarkupResemblesLocatorWarning",
  41. "UnusualUsageWarning",
  42. "XMLParsedAsHTMLWarning",
  43. ]
  44. from collections import Counter
  45. import io
  46. import sys
  47. import warnings
  48. # The very first thing we do is give a useful error if someone is
  49. # running this code under Python 2.
  50. if sys.version_info.major < 3:
  51. raise ImportError(
  52. "You are trying to use a Python 3-specific version of Beautiful Soup under Python 2. This will not work. The final version of Beautiful Soup to support Python 2 was 4.9.3."
  53. )
  54. from .builder import (
  55. builder_registry,
  56. TreeBuilder,
  57. )
  58. from .builder._htmlparser import HTMLParserTreeBuilder
  59. from .dammit import UnicodeDammit
  60. from .css import CSS
  61. from ._deprecation import (
  62. _deprecated,
  63. )
  64. from .element import (
  65. CData,
  66. Comment,
  67. DEFAULT_OUTPUT_ENCODING,
  68. Declaration,
  69. Doctype,
  70. NavigableString,
  71. PageElement,
  72. ProcessingInstruction,
  73. PYTHON_SPECIFIC_ENCODINGS,
  74. ResultSet,
  75. Script,
  76. Stylesheet,
  77. Tag,
  78. TemplateString,
  79. )
  80. from .formatter import Formatter
  81. from .filter import (
  82. ElementFilter,
  83. SoupStrainer,
  84. )
  85. from typing import (
  86. Any,
  87. cast,
  88. Counter as CounterType,
  89. Dict,
  90. Iterator,
  91. List,
  92. Sequence,
  93. Sized,
  94. Optional,
  95. Type,
  96. Union,
  97. )
  98. from bs4._typing import (
  99. _Encoding,
  100. _Encodings,
  101. _IncomingMarkup,
  102. _InsertableElement,
  103. _RawAttributeValue,
  104. _RawAttributeValues,
  105. _RawMarkup,
  106. )
  107. # Import all warnings and exceptions into the main package.
  108. from bs4.exceptions import (
  109. FeatureNotFound,
  110. ParserRejectedMarkup,
  111. StopParsing,
  112. )
  113. from bs4._warnings import (
  114. AttributeResemblesVariableWarning,
  115. GuessedAtParserWarning,
  116. MarkupResemblesLocatorWarning,
  117. UnusualUsageWarning,
  118. XMLParsedAsHTMLWarning,
  119. )
  120. class BeautifulSoup(Tag):
  121. """A data structure representing a parsed HTML or XML document.
  122. Most of the methods you'll call on a BeautifulSoup object are inherited from
  123. PageElement or Tag.
  124. Internally, this class defines the basic interface called by the
  125. tree builders when converting an HTML/XML document into a data
  126. structure. The interface abstracts away the differences between
  127. parsers. To write a new tree builder, you'll need to understand
  128. these methods as a whole.
  129. These methods will be called by the BeautifulSoup constructor:
  130. * reset()
  131. * feed(markup)
  132. The tree builder may call these methods from its feed() implementation:
  133. * handle_starttag(name, attrs) # See note about return value
  134. * handle_endtag(name)
  135. * handle_data(data) # Appends to the current data node
  136. * endData(containerClass) # Ends the current data node
  137. No matter how complicated the underlying parser is, you should be
  138. able to build a tree using 'start tag' events, 'end tag' events,
  139. 'data' events, and "done with data" events.
  140. If you encounter an empty-element tag (aka a self-closing tag,
  141. like HTML's <br> tag), call handle_starttag and then
  142. handle_endtag.
  143. """
  144. #: Since `BeautifulSoup` subclasses `Tag`, it's possible to treat it as
  145. #: a `Tag` with a `Tag.name`. Hoever, this name makes it clear the
  146. #: `BeautifulSoup` object isn't a real markup tag.
  147. ROOT_TAG_NAME: str = "[document]"
  148. #: If the end-user gives no indication which tree builder they
  149. #: want, look for one with these features.
  150. DEFAULT_BUILDER_FEATURES: Sequence[str] = ["html", "fast"]
  151. #: A string containing all ASCII whitespace characters, used in
  152. #: during parsing to detect data chunks that seem 'empty'.
  153. ASCII_SPACES: str = "\x20\x0a\x09\x0c\x0d"
  154. # FUTURE PYTHON:
  155. element_classes: Dict[Type[PageElement], Type[PageElement]] #: :meta private:
  156. builder: TreeBuilder #: :meta private:
  157. is_xml: bool
  158. known_xml: Optional[bool]
  159. parse_only: Optional[SoupStrainer] #: :meta private:
  160. # These members are only used while parsing markup.
  161. markup: Optional[_RawMarkup] #: :meta private:
  162. current_data: List[str] #: :meta private:
  163. currentTag: Optional[Tag] #: :meta private:
  164. tagStack: List[Tag] #: :meta private:
  165. open_tag_counter: CounterType[str] #: :meta private:
  166. preserve_whitespace_tag_stack: List[Tag] #: :meta private:
  167. string_container_stack: List[Tag] #: :meta private:
  168. _most_recent_element: Optional[PageElement] #: :meta private:
  169. #: Beautiful Soup's best guess as to the character encoding of the
  170. #: original document.
  171. original_encoding: Optional[_Encoding]
  172. #: The character encoding, if any, that was explicitly defined
  173. #: in the original document. This may or may not match
  174. #: `BeautifulSoup.original_encoding`.
  175. declared_html_encoding: Optional[_Encoding]
  176. #: This is True if the markup that was parsed contains
  177. #: U+FFFD REPLACEMENT_CHARACTER characters which were not present
  178. #: in the original markup. These mark character sequences that
  179. #: could not be represented in Unicode.
  180. contains_replacement_characters: bool
  181. def __init__(
  182. self,
  183. markup: _IncomingMarkup = "",
  184. features: Optional[Union[str, Sequence[str]]] = None,
  185. builder: Optional[Union[TreeBuilder, Type[TreeBuilder]]] = None,
  186. parse_only: Optional[SoupStrainer] = None,
  187. from_encoding: Optional[_Encoding] = None,
  188. exclude_encodings: Optional[_Encodings] = None,
  189. element_classes: Optional[Dict[Type[PageElement], Type[PageElement]]] = None,
  190. **kwargs: Any,
  191. ):
  192. """Constructor.
  193. :param markup: A string or a file-like object representing
  194. markup to be parsed.
  195. :param features: Desirable features of the parser to be
  196. used. This may be the name of a specific parser ("lxml",
  197. "lxml-xml", "html.parser", or "html5lib") or it may be the
  198. type of markup to be used ("html", "html5", "xml"). It's
  199. recommended that you name a specific parser, so that
  200. Beautiful Soup gives you the same results across platforms
  201. and virtual environments.
  202. :param builder: A TreeBuilder subclass to instantiate (or
  203. instance to use) instead of looking one up based on
  204. `features`. You only need to use this if you've implemented a
  205. custom TreeBuilder.
  206. :param parse_only: A SoupStrainer. Only parts of the document
  207. matching the SoupStrainer will be considered. This is useful
  208. when parsing part of a document that would otherwise be too
  209. large to fit into memory.
  210. :param from_encoding: A string indicating the encoding of the
  211. document to be parsed. Pass this in if Beautiful Soup is
  212. guessing wrongly about the document's encoding.
  213. :param exclude_encodings: A list of strings indicating
  214. encodings known to be wrong. Pass this in if you don't know
  215. the document's encoding but you know Beautiful Soup's guess is
  216. wrong.
  217. :param element_classes: A dictionary mapping BeautifulSoup
  218. classes like Tag and NavigableString, to other classes you'd
  219. like to be instantiated instead as the parse tree is
  220. built. This is useful for subclassing Tag or NavigableString
  221. to modify default behavior.
  222. :param kwargs: For backwards compatibility purposes, the
  223. constructor accepts certain keyword arguments used in
  224. Beautiful Soup 3. None of these arguments do anything in
  225. Beautiful Soup 4; they will result in a warning and then be
  226. ignored.
  227. Apart from this, any keyword arguments passed into the
  228. BeautifulSoup constructor are propagated to the TreeBuilder
  229. constructor. This makes it possible to configure a
  230. TreeBuilder by passing in arguments, not just by saying which
  231. one to use.
  232. """
  233. if "convertEntities" in kwargs:
  234. del kwargs["convertEntities"]
  235. warnings.warn(
  236. "BS4 does not respect the convertEntities argument to the "
  237. "BeautifulSoup constructor. Entities are always converted "
  238. "to Unicode characters."
  239. )
  240. if "markupMassage" in kwargs:
  241. del kwargs["markupMassage"]
  242. warnings.warn(
  243. "BS4 does not respect the markupMassage argument to the "
  244. "BeautifulSoup constructor. The tree builder is responsible "
  245. "for any necessary markup massage."
  246. )
  247. if "smartQuotesTo" in kwargs:
  248. del kwargs["smartQuotesTo"]
  249. warnings.warn(
  250. "BS4 does not respect the smartQuotesTo argument to the "
  251. "BeautifulSoup constructor. Smart quotes are always converted "
  252. "to Unicode characters."
  253. )
  254. if "selfClosingTags" in kwargs:
  255. del kwargs["selfClosingTags"]
  256. warnings.warn(
  257. "Beautiful Soup 4 does not respect the selfClosingTags argument to the "
  258. "BeautifulSoup constructor. The tree builder is responsible "
  259. "for understanding self-closing tags."
  260. )
  261. if "isHTML" in kwargs:
  262. del kwargs["isHTML"]
  263. warnings.warn(
  264. "Beautiful Soup 4 does not respect the isHTML argument to the "
  265. "BeautifulSoup constructor. Suggest you use "
  266. "features='lxml' for HTML and features='lxml-xml' for "
  267. "XML."
  268. )
  269. def deprecated_argument(old_name: str, new_name: str) -> Optional[Any]:
  270. if old_name in kwargs:
  271. warnings.warn(
  272. 'The "%s" argument to the BeautifulSoup constructor '
  273. 'was renamed to "%s" in Beautiful Soup 4.0.0'
  274. % (old_name, new_name),
  275. DeprecationWarning,
  276. stacklevel=3,
  277. )
  278. return kwargs.pop(old_name)
  279. return None
  280. parse_only = parse_only or deprecated_argument("parseOnlyThese", "parse_only")
  281. if parse_only is not None:
  282. # Issue a warning if we can tell in advance that
  283. # parse_only will exclude the entire tree.
  284. if parse_only.excludes_everything:
  285. warnings.warn(
  286. f"The given value for parse_only will exclude everything: {parse_only}",
  287. UserWarning,
  288. stacklevel=3,
  289. )
  290. from_encoding = from_encoding or deprecated_argument(
  291. "fromEncoding", "from_encoding"
  292. )
  293. if from_encoding and isinstance(markup, str):
  294. warnings.warn(
  295. "You provided Unicode markup but also provided a value for from_encoding. Your from_encoding will be ignored."
  296. )
  297. from_encoding = None
  298. self.element_classes = element_classes or dict()
  299. # We need this information to track whether or not the builder
  300. # was specified well enough that we can omit the 'you need to
  301. # specify a parser' warning.
  302. original_builder = builder
  303. original_features = features
  304. builder_class: Optional[Type[TreeBuilder]] = None
  305. if isinstance(builder, type):
  306. # A builder class was passed in; it needs to be instantiated.
  307. builder_class = builder
  308. builder = None
  309. elif builder is None:
  310. if isinstance(features, str):
  311. features = [features]
  312. if features is None or len(features) == 0:
  313. features = self.DEFAULT_BUILDER_FEATURES
  314. possible_builder_class = builder_registry.lookup(*features)
  315. if possible_builder_class is None:
  316. raise FeatureNotFound(
  317. "Couldn't find a tree builder with the features you "
  318. "requested: %s. Do you need to install a parser library?"
  319. % ",".join(features)
  320. )
  321. builder_class = possible_builder_class
  322. # At this point either we have a TreeBuilder instance in
  323. # builder, or we have a builder_class that we can instantiate
  324. # with the remaining **kwargs.
  325. if builder is None:
  326. assert builder_class is not None
  327. builder = builder_class(**kwargs)
  328. if (
  329. not original_builder
  330. and not (
  331. original_features == builder.NAME
  332. or (
  333. isinstance(original_features, str)
  334. and original_features in builder.ALTERNATE_NAMES
  335. )
  336. )
  337. and markup
  338. ):
  339. # The user did not tell us which TreeBuilder to use,
  340. # and we had to guess. Issue a warning.
  341. if builder.is_xml:
  342. markup_type = "XML"
  343. else:
  344. markup_type = "HTML"
  345. # This code adapted from warnings.py so that we get the same line
  346. # of code as our warnings.warn() call gets, even if the answer is wrong
  347. # (as it may be in a multithreading situation).
  348. caller = None
  349. try:
  350. caller = sys._getframe(1)
  351. except ValueError:
  352. pass
  353. if caller:
  354. globals = caller.f_globals
  355. line_number = caller.f_lineno
  356. else:
  357. globals = sys.__dict__
  358. line_number = 1
  359. filename = globals.get("__file__")
  360. if filename:
  361. fnl = filename.lower()
  362. if fnl.endswith((".pyc", ".pyo")):
  363. filename = filename[:-1]
  364. if filename:
  365. # If there is no filename at all, the user is most likely in a REPL,
  366. # and the warning is not necessary.
  367. values = dict(
  368. filename=filename,
  369. line_number=line_number,
  370. parser=builder.NAME,
  371. markup_type=markup_type,
  372. )
  373. warnings.warn(
  374. GuessedAtParserWarning.MESSAGE % values,
  375. GuessedAtParserWarning,
  376. stacklevel=2,
  377. )
  378. else:
  379. if kwargs:
  380. warnings.warn(
  381. "Keyword arguments to the BeautifulSoup constructor will be ignored. These would normally be passed into the TreeBuilder constructor, but a TreeBuilder instance was passed in as `builder`."
  382. )
  383. self.builder = builder
  384. self.is_xml = builder.is_xml
  385. self.known_xml = self.is_xml
  386. self._namespaces = dict()
  387. self.parse_only = parse_only
  388. if hasattr(markup, "read"): # It's a file-type object.
  389. markup = cast(io.IOBase, markup).read()
  390. elif not isinstance(markup, (bytes, str)) and not hasattr(markup, "__len__"):
  391. raise TypeError(
  392. f"Incoming markup is of an invalid type: {markup!r}. Markup must be a string, a bytestring, or an open filehandle."
  393. )
  394. elif isinstance(markup, Sized) and len(markup) <= 256 and (
  395. (isinstance(markup, bytes) and b"<" not in markup and b"\n" not in markup)
  396. or (isinstance(markup, str) and "<" not in markup and "\n" not in markup)
  397. ):
  398. # Issue warnings for a couple beginner problems
  399. # involving passing non-markup to Beautiful Soup.
  400. # Beautiful Soup will still parse the input as markup,
  401. # since that is sometimes the intended behavior.
  402. if not self._markup_is_url(markup):
  403. self._markup_resembles_filename(markup)
  404. # At this point we know markup is a string or bytestring. If
  405. # it was a file-type object, we've read from it.
  406. markup = cast(_RawMarkup, markup)
  407. rejections = []
  408. success = False
  409. for (
  410. self.markup,
  411. self.original_encoding,
  412. self.declared_html_encoding,
  413. self.contains_replacement_characters,
  414. ) in self.builder.prepare_markup(
  415. markup, from_encoding, exclude_encodings=exclude_encodings
  416. ):
  417. self.reset()
  418. self.builder.initialize_soup(self)
  419. try:
  420. self._feed()
  421. success = True
  422. break
  423. except ParserRejectedMarkup as e:
  424. rejections.append(e)
  425. pass
  426. if not success:
  427. other_exceptions = [str(e) for e in rejections]
  428. raise ParserRejectedMarkup(
  429. "The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help.\n\nOriginal exception(s) from parser:\n "
  430. + "\n ".join(other_exceptions)
  431. )
  432. # Clear out the markup and remove the builder's circular
  433. # reference to this object.
  434. self.markup = None
  435. self.builder.soup = None
  436. def copy_self(self) -> "BeautifulSoup":
  437. """Create a new BeautifulSoup object with the same TreeBuilder,
  438. but not associated with any markup.
  439. This is the first step of the deepcopy process.
  440. """
  441. clone = type(self)("", None, self.builder)
  442. # Keep track of the encoding of the original document,
  443. # since we won't be parsing it again.
  444. clone.original_encoding = self.original_encoding
  445. return clone
  446. def __getstate__(self) -> Dict[str, Any]:
  447. # Frequently a tree builder can't be pickled.
  448. d = dict(self.__dict__)
  449. if "builder" in d and d["builder"] is not None and not self.builder.picklable:
  450. d["builder"] = type(self.builder)
  451. # Store the contents as a Unicode string.
  452. d["contents"] = []
  453. d["markup"] = self.decode()
  454. # If _most_recent_element is present, it's a Tag object left
  455. # over from initial parse. It might not be picklable and we
  456. # don't need it.
  457. if "_most_recent_element" in d:
  458. del d["_most_recent_element"]
  459. return d
  460. def __setstate__(self, state: Dict[str, Any]) -> None:
  461. # If necessary, restore the TreeBuilder by looking it up.
  462. self.__dict__ = state
  463. if isinstance(self.builder, type):
  464. self.builder = self.builder()
  465. elif not self.builder:
  466. # We don't know which builder was used to build this
  467. # parse tree, so use a default we know is always available.
  468. self.builder = HTMLParserTreeBuilder()
  469. self.builder.soup = self
  470. self.reset()
  471. self._feed()
  472. @classmethod
  473. @_deprecated(
  474. replaced_by="nothing (private method, will be removed)", version="4.13.0"
  475. )
  476. def _decode_markup(cls, markup: _RawMarkup) -> str:
  477. """Ensure `markup` is Unicode so it's safe to send into warnings.warn.
  478. warnings.warn had this problem back in 2010 but fortunately
  479. not anymore. This has not been used for a long time; I just
  480. noticed that fact while working on 4.13.0.
  481. """
  482. if isinstance(markup, bytes):
  483. decoded = markup.decode("utf-8", "replace")
  484. else:
  485. decoded = markup
  486. return decoded
  487. @classmethod
  488. def _markup_is_url(cls, markup: _RawMarkup) -> bool:
  489. """Error-handling method to raise a warning if incoming markup looks
  490. like a URL.
  491. :param markup: A string of markup.
  492. :return: Whether or not the markup resembled a URL
  493. closely enough to justify issuing a warning.
  494. """
  495. problem: bool = False
  496. if isinstance(markup, bytes):
  497. problem = (
  498. any(markup.startswith(prefix) for prefix in (b"http:", b"https:"))
  499. and b" " not in markup
  500. )
  501. elif isinstance(markup, str):
  502. problem = (
  503. any(markup.startswith(prefix) for prefix in ("http:", "https:"))
  504. and " " not in markup
  505. )
  506. else:
  507. return False
  508. if not problem:
  509. return False
  510. warnings.warn(
  511. MarkupResemblesLocatorWarning.URL_MESSAGE % dict(what="URL"),
  512. MarkupResemblesLocatorWarning,
  513. stacklevel=3,
  514. )
  515. return True
  516. @classmethod
  517. def _markup_resembles_filename(cls, markup: _RawMarkup) -> bool:
  518. """Error-handling method to issue a warning if incoming markup
  519. resembles a filename.
  520. :param markup: A string of markup.
  521. :return: Whether or not the markup resembled a filename
  522. closely enough to justify issuing a warning.
  523. """
  524. markup_b: bytes
  525. # We're only checking ASCII characters, so rather than write
  526. # the same tests twice, convert Unicode to a bytestring and
  527. # operate on the bytestring.
  528. if isinstance(markup, str):
  529. markup_b = markup.encode("utf8")
  530. else:
  531. markup_b = markup
  532. # Step 1: does it end with a common textual file extension?
  533. filelike = False
  534. lower = markup_b.lower()
  535. extensions = [b".html", b".htm", b".xml", b".xhtml", b".txt"]
  536. if any(lower.endswith(ext) for ext in extensions):
  537. filelike = True
  538. if not filelike:
  539. return False
  540. # Step 2: it _might_ be a file, but there are a few things
  541. # we can look for that aren't very common in filenames.
  542. # Characters that have special meaning to Unix shells. (< was
  543. # excluded before this method was called.)
  544. #
  545. # Many of these are also reserved characters that cannot
  546. # appear in Windows filenames.
  547. for byte in markup_b:
  548. if byte in b"?*#&;>$|":
  549. return False
  550. # Two consecutive forward slashes (as seen in a URL) or two
  551. # consecutive spaces (as seen in fixed-width data).
  552. #
  553. # (Paths to Windows network shares contain consecutive
  554. # backslashes, so checking that doesn't seem as helpful.)
  555. if b"//" in markup_b:
  556. return False
  557. if b" " in markup_b:
  558. return False
  559. # A colon in any position other than position 1 (e.g. after a
  560. # Windows drive letter).
  561. if markup_b.startswith(b":"):
  562. return False
  563. colon_i = markup_b.rfind(b":")
  564. if colon_i not in (-1, 1):
  565. return False
  566. # Step 3: If it survived all of those checks, it's similar
  567. # enough to a file to justify issuing a warning.
  568. warnings.warn(
  569. MarkupResemblesLocatorWarning.FILENAME_MESSAGE % dict(what="filename"),
  570. MarkupResemblesLocatorWarning,
  571. stacklevel=3,
  572. )
  573. return True
  574. def _feed(self) -> None:
  575. """Internal method that parses previously set markup, creating a large
  576. number of Tag and NavigableString objects.
  577. """
  578. # Convert the document to Unicode.
  579. self.builder.reset()
  580. if self.markup is not None:
  581. self.builder.feed(self.markup)
  582. # Close out any unfinished strings and close all the open tags.
  583. self.endData()
  584. while (
  585. self.currentTag is not None and self.currentTag.name != self.ROOT_TAG_NAME
  586. ):
  587. self.popTag()
  588. def reset(self) -> None:
  589. """Reset this object to a state as though it had never parsed any
  590. markup.
  591. """
  592. Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME)
  593. self.hidden = True
  594. self.builder.reset()
  595. self.current_data = []
  596. self.currentTag = None
  597. self.tagStack = []
  598. self.open_tag_counter = Counter()
  599. self.preserve_whitespace_tag_stack = []
  600. self.string_container_stack = []
  601. self._most_recent_element = None
  602. self.pushTag(self)
  603. def new_tag(
  604. self,
  605. name: str,
  606. namespace: Optional[str] = None,
  607. nsprefix: Optional[str] = None,
  608. attrs: Optional[_RawAttributeValues] = None,
  609. sourceline: Optional[int] = None,
  610. sourcepos: Optional[int] = None,
  611. string: Optional[str] = None,
  612. **kwattrs: _RawAttributeValue,
  613. ) -> Tag:
  614. """Create a new Tag associated with this BeautifulSoup object.
  615. :param name: The name of the new Tag.
  616. :param namespace: The URI of the new Tag's XML namespace, if any.
  617. :param prefix: The prefix for the new Tag's XML namespace, if any.
  618. :param attrs: A dictionary of this Tag's attribute values; can
  619. be used instead of ``kwattrs`` for attributes like 'class'
  620. that are reserved words in Python.
  621. :param sourceline: The line number where this tag was
  622. (purportedly) found in its source document.
  623. :param sourcepos: The character position within ``sourceline`` where this
  624. tag was (purportedly) found.
  625. :param string: String content for the new Tag, if any.
  626. :param kwattrs: Keyword arguments for the new Tag's attribute values.
  627. """
  628. attr_container = self.builder.attribute_dict_class(**kwattrs)
  629. if attrs is not None:
  630. attr_container.update(attrs)
  631. tag_class = self.element_classes.get(Tag, Tag)
  632. # Assume that this is either Tag or a subclass of Tag. If not,
  633. # the user brought type-unsafety upon themselves.
  634. tag_class = cast(Type[Tag], tag_class)
  635. tag = tag_class(
  636. None,
  637. self.builder,
  638. name,
  639. namespace,
  640. nsprefix,
  641. attr_container,
  642. sourceline=sourceline,
  643. sourcepos=sourcepos,
  644. )
  645. if string is not None:
  646. tag.string = string
  647. return tag
  648. def string_container(
  649. self, base_class: Optional[Type[NavigableString]] = None
  650. ) -> Type[NavigableString]:
  651. """Find the class that should be instantiated to hold a given kind of
  652. string.
  653. This may be a built-in Beautiful Soup class or a custom class passed
  654. in to the BeautifulSoup constructor.
  655. """
  656. container = base_class or NavigableString
  657. # The user may want us to use some other class (hopefully a
  658. # custom subclass) instead of the one we'd use normally.
  659. container = cast(
  660. Type[NavigableString], self.element_classes.get(container, container)
  661. )
  662. # On top of that, we may be inside a tag that needs a special
  663. # container class.
  664. if self.string_container_stack and container is NavigableString:
  665. container = self.builder.string_containers.get(
  666. self.string_container_stack[-1].name, container
  667. )
  668. return container
  669. def new_string(
  670. self, s: str, subclass: Optional[Type[NavigableString]] = None
  671. ) -> NavigableString:
  672. """Create a new `NavigableString` associated with this `BeautifulSoup`
  673. object.
  674. :param s: The string content of the `NavigableString`
  675. :param subclass: The subclass of `NavigableString`, if any, to
  676. use. If a document is being processed, an appropriate
  677. subclass for the current location in the document will
  678. be determined automatically.
  679. """
  680. container = self.string_container(subclass)
  681. return container(s)
  682. def insert_before(self, *args: _InsertableElement) -> List[PageElement]:
  683. """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement
  684. it because there is nothing before or after it in the parse tree.
  685. """
  686. raise NotImplementedError(
  687. "BeautifulSoup objects don't support insert_before()."
  688. )
  689. def insert_after(self, *args: _InsertableElement) -> List[PageElement]:
  690. """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement
  691. it because there is nothing before or after it in the parse tree.
  692. """
  693. raise NotImplementedError("BeautifulSoup objects don't support insert_after().")
  694. def popTag(self) -> Optional[Tag]:
  695. """Internal method called by _popToTag when a tag is closed.
  696. :meta private:
  697. """
  698. if not self.tagStack:
  699. # Nothing to pop. This shouldn't happen.
  700. return None
  701. tag = self.tagStack.pop()
  702. if tag.name in self.open_tag_counter:
  703. self.open_tag_counter[tag.name] -= 1
  704. if (
  705. self.preserve_whitespace_tag_stack
  706. and tag == self.preserve_whitespace_tag_stack[-1]
  707. ):
  708. self.preserve_whitespace_tag_stack.pop()
  709. if self.string_container_stack and tag == self.string_container_stack[-1]:
  710. self.string_container_stack.pop()
  711. # print("Pop", tag.name)
  712. if self.tagStack:
  713. self.currentTag = self.tagStack[-1]
  714. return self.currentTag
  715. def pushTag(self, tag: Tag) -> None:
  716. """Internal method called by handle_starttag when a tag is opened.
  717. :meta private:
  718. """
  719. # print("Push", tag.name)
  720. if self.currentTag is not None:
  721. self.currentTag.contents.append(tag)
  722. self.tagStack.append(tag)
  723. self.currentTag = self.tagStack[-1]
  724. if tag.name != self.ROOT_TAG_NAME:
  725. self.open_tag_counter[tag.name] += 1
  726. if tag.name in self.builder.preserve_whitespace_tags:
  727. self.preserve_whitespace_tag_stack.append(tag)
  728. if tag.name in self.builder.string_containers:
  729. self.string_container_stack.append(tag)
  730. def endData(self, containerClass: Optional[Type[NavigableString]] = None) -> None:
  731. """Method called by the TreeBuilder when the end of a data segment
  732. occurs.
  733. :param containerClass: The class to use when incorporating the
  734. data segment into the parse tree.
  735. :meta private:
  736. """
  737. if self.current_data:
  738. current_data = "".join(self.current_data)
  739. # If whitespace is not preserved, and this string contains
  740. # nothing but ASCII spaces, replace it with a single space
  741. # or newline.
  742. if not self.preserve_whitespace_tag_stack:
  743. strippable = True
  744. for i in current_data:
  745. if i not in self.ASCII_SPACES:
  746. strippable = False
  747. break
  748. if strippable:
  749. if "\n" in current_data:
  750. current_data = "\n"
  751. else:
  752. current_data = " "
  753. # Reset the data collector.
  754. self.current_data = []
  755. # Should we add this string to the tree at all?
  756. if (
  757. self.parse_only
  758. and len(self.tagStack) <= 1
  759. and (not self.parse_only.allow_string_creation(current_data))
  760. ):
  761. return
  762. containerClass = self.string_container(containerClass)
  763. o = containerClass(current_data)
  764. self.object_was_parsed(o)
  765. def object_was_parsed(
  766. self,
  767. o: PageElement,
  768. parent: Optional[Tag] = None,
  769. most_recent_element: Optional[PageElement] = None,
  770. ) -> None:
  771. """Method called by the TreeBuilder to integrate an object into the
  772. parse tree.
  773. :meta private:
  774. """
  775. if parent is None:
  776. parent = self.currentTag
  777. assert parent is not None
  778. previous_element: Optional[PageElement]
  779. if most_recent_element is not None:
  780. previous_element = most_recent_element
  781. else:
  782. previous_element = self._most_recent_element
  783. next_element = previous_sibling = next_sibling = None
  784. if isinstance(o, Tag):
  785. next_element = o.next_element
  786. next_sibling = o.next_sibling
  787. previous_sibling = o.previous_sibling
  788. if previous_element is None:
  789. previous_element = o.previous_element
  790. fix = parent.next_element is not None
  791. o.setup(parent, previous_element, next_element, previous_sibling, next_sibling)
  792. self._most_recent_element = o
  793. parent.contents.append(o)
  794. # Check if we are inserting into an already parsed node.
  795. if fix:
  796. self._linkage_fixer(parent)
  797. def _linkage_fixer(self, el: Tag) -> None:
  798. """Make sure linkage of this fragment is sound."""
  799. first = el.contents[0]
  800. child = el.contents[-1]
  801. descendant: PageElement = child
  802. if child is first and el.parent is not None:
  803. # Parent should be linked to first child
  804. el.next_element = child
  805. # We are no longer linked to whatever this element is
  806. prev_el = child.previous_element
  807. if prev_el is not None and prev_el is not el:
  808. prev_el.next_element = None
  809. # First child should be linked to the parent, and no previous siblings.
  810. child.previous_element = el
  811. child.previous_sibling = None
  812. # We have no sibling as we've been appended as the last.
  813. child.next_sibling = None
  814. # This index is a tag, dig deeper for a "last descendant"
  815. if isinstance(child, Tag) and child.contents:
  816. # _last_decendant is typed as returning Optional[PageElement],
  817. # but the value can't be None here, because el is a Tag
  818. # which we know has contents.
  819. descendant = cast(PageElement, child._last_descendant(False))
  820. # As the final step, link last descendant. It should be linked
  821. # to the parent's next sibling (if found), else walk up the chain
  822. # and find a parent with a sibling. It should have no next sibling.
  823. descendant.next_element = None
  824. descendant.next_sibling = None
  825. target: Optional[Tag] = el
  826. while True:
  827. if target is None:
  828. break
  829. elif target.next_sibling is not None:
  830. descendant.next_element = target.next_sibling
  831. target.next_sibling.previous_element = child
  832. break
  833. target = target.parent
  834. def _popToTag(
  835. self, name: str, nsprefix: Optional[str] = None, inclusivePop: bool = True
  836. ) -> Optional[Tag]:
  837. """Pops the tag stack up to and including the most recent
  838. instance of the given tag.
  839. If there are no open tags with the given name, nothing will be
  840. popped.
  841. :param name: Pop up to the most recent tag with this name.
  842. :param nsprefix: The namespace prefix that goes with `name`.
  843. :param inclusivePop: It this is false, pops the tag stack up
  844. to but *not* including the most recent instqance of the
  845. given tag.
  846. :meta private:
  847. """
  848. # print("Popping to %s" % name)
  849. if name == self.ROOT_TAG_NAME:
  850. # The BeautifulSoup object itself can never be popped.
  851. return None
  852. most_recently_popped = None
  853. stack_size = len(self.tagStack)
  854. for i in range(stack_size - 1, 0, -1):
  855. if not self.open_tag_counter.get(name):
  856. break
  857. t = self.tagStack[i]
  858. if name == t.name and nsprefix == t.prefix:
  859. if inclusivePop:
  860. most_recently_popped = self.popTag()
  861. break
  862. most_recently_popped = self.popTag()
  863. return most_recently_popped
  864. def handle_starttag(
  865. self,
  866. name: str,
  867. namespace: Optional[str],
  868. nsprefix: Optional[str],
  869. attrs: _RawAttributeValues,
  870. sourceline: Optional[int] = None,
  871. sourcepos: Optional[int] = None,
  872. namespaces: Optional[Dict[str, str]] = None,
  873. ) -> Optional[Tag]:
  874. """Called by the tree builder when a new tag is encountered.
  875. :param name: Name of the tag.
  876. :param nsprefix: Namespace prefix for the tag.
  877. :param attrs: A dictionary of attribute values. Note that
  878. attribute values are expected to be simple strings; processing
  879. of multi-valued attributes such as "class" comes later.
  880. :param sourceline: The line number where this tag was found in its
  881. source document.
  882. :param sourcepos: The character position within `sourceline` where this
  883. tag was found.
  884. :param namespaces: A dictionary of all namespace prefix mappings
  885. currently in scope in the document.
  886. If this method returns None, the tag was rejected by an active
  887. `ElementFilter`. You should proceed as if the tag had not occurred
  888. in the document. For instance, if this was a self-closing tag,
  889. don't call handle_endtag.
  890. :meta private:
  891. """
  892. # print("Start tag %s: %s" % (name, attrs))
  893. self.endData()
  894. if (
  895. self.parse_only
  896. and len(self.tagStack) <= 1
  897. and not self.parse_only.allow_tag_creation(nsprefix, name, attrs)
  898. ):
  899. return None
  900. tag_class = self.element_classes.get(Tag, Tag)
  901. # Assume that this is either Tag or a subclass of Tag. If not,
  902. # the user brought type-unsafety upon themselves.
  903. tag_class = cast(Type[Tag], tag_class)
  904. tag = tag_class(
  905. self,
  906. self.builder,
  907. name,
  908. namespace,
  909. nsprefix,
  910. attrs,
  911. self.currentTag,
  912. self._most_recent_element,
  913. sourceline=sourceline,
  914. sourcepos=sourcepos,
  915. namespaces=namespaces,
  916. )
  917. if tag is None:
  918. return tag
  919. if self._most_recent_element is not None:
  920. self._most_recent_element.next_element = tag
  921. self._most_recent_element = tag
  922. self.pushTag(tag)
  923. return tag
  924. def handle_endtag(self, name: str, nsprefix: Optional[str] = None) -> None:
  925. """Called by the tree builder when an ending tag is encountered.
  926. :param name: Name of the tag.
  927. :param nsprefix: Namespace prefix for the tag.
  928. :meta private:
  929. """
  930. # print("End tag: " + name)
  931. self.endData()
  932. self._popToTag(name, nsprefix)
  933. def handle_data(self, data: str) -> None:
  934. """Called by the tree builder when a chunk of textual data is
  935. encountered.
  936. :meta private:
  937. """
  938. self.current_data.append(data)
  939. def decode(
  940. self,
  941. indent_level: Optional[int] = None,
  942. eventual_encoding: _Encoding = DEFAULT_OUTPUT_ENCODING,
  943. formatter: Union[Formatter, str] = "minimal",
  944. iterator: Optional[Iterator[PageElement]] = None,
  945. **kwargs: Any,
  946. ) -> str:
  947. """Returns a string representation of the parse tree
  948. as a full HTML or XML document.
  949. :param indent_level: Each line of the rendering will be
  950. indented this many levels. (The ``formatter`` decides what a
  951. 'level' means, in terms of spaces or other characters
  952. output.) This is used internally in recursive calls while
  953. pretty-printing.
  954. :param eventual_encoding: The encoding of the final document.
  955. If this is None, the document will be a Unicode string.
  956. :param formatter: Either a `Formatter` object, or a string naming one of
  957. the standard formatters.
  958. :param iterator: The iterator to use when navigating over the
  959. parse tree. This is only used by `Tag.decode_contents` and
  960. you probably won't need to use it.
  961. """
  962. if self.is_xml:
  963. # Print the XML declaration
  964. encoding_part = ""
  965. declared_encoding: Optional[str] = eventual_encoding
  966. if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS:
  967. # This is a special Python encoding; it can't actually
  968. # go into an XML document because it means nothing
  969. # outside of Python.
  970. declared_encoding = None
  971. if declared_encoding is not None:
  972. encoding_part = ' encoding="%s"' % declared_encoding
  973. prefix = '<?xml version="1.0"%s?>\n' % encoding_part
  974. else:
  975. prefix = ""
  976. # Prior to 4.13.0, the first argument to this method was a
  977. # bool called pretty_print, which gave the method a different
  978. # signature from its superclass implementation, Tag.decode.
  979. #
  980. # The signatures of the two methods now match, but just in
  981. # case someone is still passing a boolean in as the first
  982. # argument to this method (or a keyword argument with the old
  983. # name), we can handle it and put out a DeprecationWarning.
  984. warning: Optional[str] = None
  985. pretty_print: Optional[bool] = None
  986. if isinstance(indent_level, bool):
  987. if indent_level is True:
  988. indent_level = 0
  989. elif indent_level is False:
  990. indent_level = None
  991. warning = f"As of 4.13.0, the first argument to BeautifulSoup.decode has been changed from bool to int, to match Tag.decode. Pass in a value of {indent_level} instead."
  992. else:
  993. pretty_print = kwargs.pop("pretty_print", None)
  994. assert not kwargs
  995. if pretty_print is not None:
  996. if pretty_print is True:
  997. indent_level = 0
  998. elif pretty_print is False:
  999. indent_level = None
  1000. warning = f"As of 4.13.0, the pretty_print argument to BeautifulSoup.decode has been removed, to match Tag.decode. Pass in a value of indent_level={indent_level} instead."
  1001. if warning:
  1002. warnings.warn(warning, DeprecationWarning, stacklevel=2)
  1003. elif indent_level is False or pretty_print is False:
  1004. indent_level = None
  1005. return prefix + super(BeautifulSoup, self).decode(
  1006. indent_level, eventual_encoding, formatter, iterator
  1007. )
  1008. # Aliases to make it easier to get started quickly, e.g. 'from bs4 import _soup'
  1009. _s = BeautifulSoup
  1010. _soup = BeautifulSoup
  1011. class BeautifulStoneSoup(BeautifulSoup):
  1012. """Deprecated interface to an XML parser."""
  1013. def __init__(self, *args: Any, **kwargs: Any):
  1014. kwargs["features"] = "xml"
  1015. warnings.warn(
  1016. "The BeautifulStoneSoup class was deprecated in version 4.0.0. Instead of using "
  1017. 'it, pass features="xml" into the BeautifulSoup constructor.',
  1018. DeprecationWarning,
  1019. stacklevel=2,
  1020. )
  1021. super(BeautifulStoneSoup, self).__init__(*args, **kwargs)
  1022. # If this file is run as a script, act as an HTML pretty-printer.
  1023. if __name__ == "__main__":
  1024. import sys
  1025. soup = BeautifulSoup(sys.stdin)
  1026. print((soup.prettify()))