__init__.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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.6 and up. It works better if lxml
  8. and/or html5lib is installed.
  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.12.3"
  14. __copyright__ = "Copyright (c) 2004-2024 Leonard Richardson"
  15. # Use of this source code is governed by the MIT license.
  16. __license__ = "MIT"
  17. __all__ = ['BeautifulSoup']
  18. from collections import Counter
  19. import os
  20. import re
  21. import sys
  22. import traceback
  23. import warnings
  24. # The very first thing we do is give a useful error if someone is
  25. # running this code under Python 2.
  26. if sys.version_info.major < 3:
  27. raise ImportError('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.')
  28. from .builder import (
  29. builder_registry,
  30. ParserRejectedMarkup,
  31. XMLParsedAsHTMLWarning,
  32. HTMLParserTreeBuilder
  33. )
  34. from .dammit import UnicodeDammit
  35. from .element import (
  36. CData,
  37. Comment,
  38. CSS,
  39. DEFAULT_OUTPUT_ENCODING,
  40. Declaration,
  41. Doctype,
  42. NavigableString,
  43. PageElement,
  44. ProcessingInstruction,
  45. PYTHON_SPECIFIC_ENCODINGS,
  46. ResultSet,
  47. Script,
  48. Stylesheet,
  49. SoupStrainer,
  50. Tag,
  51. TemplateString,
  52. )
  53. # Define some custom warnings.
  54. class GuessedAtParserWarning(UserWarning):
  55. """The warning issued when BeautifulSoup has to guess what parser to
  56. use -- probably because no parser was specified in the constructor.
  57. """
  58. class MarkupResemblesLocatorWarning(UserWarning):
  59. """The warning issued when BeautifulSoup is given 'markup' that
  60. actually looks like a resource locator -- a URL or a path to a file
  61. on disk.
  62. """
  63. class BeautifulSoup(Tag):
  64. """A data structure representing a parsed HTML or XML document.
  65. Most of the methods you'll call on a BeautifulSoup object are inherited from
  66. PageElement or Tag.
  67. Internally, this class defines the basic interface called by the
  68. tree builders when converting an HTML/XML document into a data
  69. structure. The interface abstracts away the differences between
  70. parsers. To write a new tree builder, you'll need to understand
  71. these methods as a whole.
  72. These methods will be called by the BeautifulSoup constructor:
  73. * reset()
  74. * feed(markup)
  75. The tree builder may call these methods from its feed() implementation:
  76. * handle_starttag(name, attrs) # See note about return value
  77. * handle_endtag(name)
  78. * handle_data(data) # Appends to the current data node
  79. * endData(containerClass) # Ends the current data node
  80. No matter how complicated the underlying parser is, you should be
  81. able to build a tree using 'start tag' events, 'end tag' events,
  82. 'data' events, and "done with data" events.
  83. If you encounter an empty-element tag (aka a self-closing tag,
  84. like HTML's <br> tag), call handle_starttag and then
  85. handle_endtag.
  86. """
  87. # Since BeautifulSoup subclasses Tag, it's possible to treat it as
  88. # a Tag with a .name. This name makes it clear the BeautifulSoup
  89. # object isn't a real markup tag.
  90. ROOT_TAG_NAME = '[document]'
  91. # If the end-user gives no indication which tree builder they
  92. # want, look for one with these features.
  93. DEFAULT_BUILDER_FEATURES = ['html', 'fast']
  94. # A string containing all ASCII whitespace characters, used in
  95. # endData() to detect data chunks that seem 'empty'.
  96. ASCII_SPACES = '\x20\x0a\x09\x0c\x0d'
  97. NO_PARSER_SPECIFIED_WARNING = "No parser was explicitly specified, so I'm using the best available %(markup_type)s parser for this system (\"%(parser)s\"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.\n\nThe code that caused this warning is on line %(line_number)s of the file %(filename)s. To get rid of this warning, pass the additional argument 'features=\"%(parser)s\"' to the BeautifulSoup constructor.\n"
  98. def __init__(self, markup="", features=None, builder=None,
  99. parse_only=None, from_encoding=None, exclude_encodings=None,
  100. element_classes=None, **kwargs):
  101. """Constructor.
  102. :param markup: A string or a file-like object representing
  103. markup to be parsed.
  104. :param features: Desirable features of the parser to be
  105. used. This may be the name of a specific parser ("lxml",
  106. "lxml-xml", "html.parser", or "html5lib") or it may be the
  107. type of markup to be used ("html", "html5", "xml"). It's
  108. recommended that you name a specific parser, so that
  109. Beautiful Soup gives you the same results across platforms
  110. and virtual environments.
  111. :param builder: A TreeBuilder subclass to instantiate (or
  112. instance to use) instead of looking one up based on
  113. `features`. You only need to use this if you've implemented a
  114. custom TreeBuilder.
  115. :param parse_only: A SoupStrainer. Only parts of the document
  116. matching the SoupStrainer will be considered. This is useful
  117. when parsing part of a document that would otherwise be too
  118. large to fit into memory.
  119. :param from_encoding: A string indicating the encoding of the
  120. document to be parsed. Pass this in if Beautiful Soup is
  121. guessing wrongly about the document's encoding.
  122. :param exclude_encodings: A list of strings indicating
  123. encodings known to be wrong. Pass this in if you don't know
  124. the document's encoding but you know Beautiful Soup's guess is
  125. wrong.
  126. :param element_classes: A dictionary mapping BeautifulSoup
  127. classes like Tag and NavigableString, to other classes you'd
  128. like to be instantiated instead as the parse tree is
  129. built. This is useful for subclassing Tag or NavigableString
  130. to modify default behavior.
  131. :param kwargs: For backwards compatibility purposes, the
  132. constructor accepts certain keyword arguments used in
  133. Beautiful Soup 3. None of these arguments do anything in
  134. Beautiful Soup 4; they will result in a warning and then be
  135. ignored.
  136. Apart from this, any keyword arguments passed into the
  137. BeautifulSoup constructor are propagated to the TreeBuilder
  138. constructor. This makes it possible to configure a
  139. TreeBuilder by passing in arguments, not just by saying which
  140. one to use.
  141. """
  142. if 'convertEntities' in kwargs:
  143. del kwargs['convertEntities']
  144. warnings.warn(
  145. "BS4 does not respect the convertEntities argument to the "
  146. "BeautifulSoup constructor. Entities are always converted "
  147. "to Unicode characters.")
  148. if 'markupMassage' in kwargs:
  149. del kwargs['markupMassage']
  150. warnings.warn(
  151. "BS4 does not respect the markupMassage argument to the "
  152. "BeautifulSoup constructor. The tree builder is responsible "
  153. "for any necessary markup massage.")
  154. if 'smartQuotesTo' in kwargs:
  155. del kwargs['smartQuotesTo']
  156. warnings.warn(
  157. "BS4 does not respect the smartQuotesTo argument to the "
  158. "BeautifulSoup constructor. Smart quotes are always converted "
  159. "to Unicode characters.")
  160. if 'selfClosingTags' in kwargs:
  161. del kwargs['selfClosingTags']
  162. warnings.warn(
  163. "BS4 does not respect the selfClosingTags argument to the "
  164. "BeautifulSoup constructor. The tree builder is responsible "
  165. "for understanding self-closing tags.")
  166. if 'isHTML' in kwargs:
  167. del kwargs['isHTML']
  168. warnings.warn(
  169. "BS4 does not respect the isHTML argument to the "
  170. "BeautifulSoup constructor. Suggest you use "
  171. "features='lxml' for HTML and features='lxml-xml' for "
  172. "XML.")
  173. def deprecated_argument(old_name, new_name):
  174. if old_name in kwargs:
  175. warnings.warn(
  176. 'The "%s" argument to the BeautifulSoup constructor '
  177. 'has been renamed to "%s."' % (old_name, new_name),
  178. DeprecationWarning, stacklevel=3
  179. )
  180. return kwargs.pop(old_name)
  181. return None
  182. parse_only = parse_only or deprecated_argument(
  183. "parseOnlyThese", "parse_only")
  184. from_encoding = from_encoding or deprecated_argument(
  185. "fromEncoding", "from_encoding")
  186. if from_encoding and isinstance(markup, str):
  187. warnings.warn("You provided Unicode markup but also provided a value for from_encoding. Your from_encoding will be ignored.")
  188. from_encoding = None
  189. self.element_classes = element_classes or dict()
  190. # We need this information to track whether or not the builder
  191. # was specified well enough that we can omit the 'you need to
  192. # specify a parser' warning.
  193. original_builder = builder
  194. original_features = features
  195. if isinstance(builder, type):
  196. # A builder class was passed in; it needs to be instantiated.
  197. builder_class = builder
  198. builder = None
  199. elif builder is None:
  200. if isinstance(features, str):
  201. features = [features]
  202. if features is None or len(features) == 0:
  203. features = self.DEFAULT_BUILDER_FEATURES
  204. builder_class = builder_registry.lookup(*features)
  205. if builder_class is None:
  206. raise FeatureNotFound(
  207. "Couldn't find a tree builder with the features you "
  208. "requested: %s. Do you need to install a parser library?"
  209. % ",".join(features))
  210. # At this point either we have a TreeBuilder instance in
  211. # builder, or we have a builder_class that we can instantiate
  212. # with the remaining **kwargs.
  213. if builder is None:
  214. builder = builder_class(**kwargs)
  215. if not original_builder and not (
  216. original_features == builder.NAME or
  217. original_features in builder.ALTERNATE_NAMES
  218. ) and markup:
  219. # The user did not tell us which TreeBuilder to use,
  220. # and we had to guess. Issue a warning.
  221. if builder.is_xml:
  222. markup_type = "XML"
  223. else:
  224. markup_type = "HTML"
  225. # This code adapted from warnings.py so that we get the same line
  226. # of code as our warnings.warn() call gets, even if the answer is wrong
  227. # (as it may be in a multithreading situation).
  228. caller = None
  229. try:
  230. caller = sys._getframe(1)
  231. except ValueError:
  232. pass
  233. if caller:
  234. globals = caller.f_globals
  235. line_number = caller.f_lineno
  236. else:
  237. globals = sys.__dict__
  238. line_number= 1
  239. filename = globals.get('__file__')
  240. if filename:
  241. fnl = filename.lower()
  242. if fnl.endswith((".pyc", ".pyo")):
  243. filename = filename[:-1]
  244. if filename:
  245. # If there is no filename at all, the user is most likely in a REPL,
  246. # and the warning is not necessary.
  247. values = dict(
  248. filename=filename,
  249. line_number=line_number,
  250. parser=builder.NAME,
  251. markup_type=markup_type
  252. )
  253. warnings.warn(
  254. self.NO_PARSER_SPECIFIED_WARNING % values,
  255. GuessedAtParserWarning, stacklevel=2
  256. )
  257. else:
  258. if kwargs:
  259. warnings.warn("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`.")
  260. self.builder = builder
  261. self.is_xml = builder.is_xml
  262. self.known_xml = self.is_xml
  263. self._namespaces = dict()
  264. self.parse_only = parse_only
  265. if hasattr(markup, 'read'): # It's a file-type object.
  266. markup = markup.read()
  267. elif len(markup) <= 256 and (
  268. (isinstance(markup, bytes) and not b'<' in markup)
  269. or (isinstance(markup, str) and not '<' in markup)
  270. ):
  271. # Issue warnings for a couple beginner problems
  272. # involving passing non-markup to Beautiful Soup.
  273. # Beautiful Soup will still parse the input as markup,
  274. # since that is sometimes the intended behavior.
  275. if not self._markup_is_url(markup):
  276. self._markup_resembles_filename(markup)
  277. rejections = []
  278. success = False
  279. for (self.markup, self.original_encoding, self.declared_html_encoding,
  280. self.contains_replacement_characters) in (
  281. self.builder.prepare_markup(
  282. markup, from_encoding, exclude_encodings=exclude_encodings)):
  283. self.reset()
  284. self.builder.initialize_soup(self)
  285. try:
  286. self._feed()
  287. success = True
  288. break
  289. except ParserRejectedMarkup as e:
  290. rejections.append(e)
  291. pass
  292. if not success:
  293. other_exceptions = [str(e) for e in rejections]
  294. raise ParserRejectedMarkup(
  295. "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 " + "\n ".join(other_exceptions)
  296. )
  297. # Clear out the markup and remove the builder's circular
  298. # reference to this object.
  299. self.markup = None
  300. self.builder.soup = None
  301. def _clone(self):
  302. """Create a new BeautifulSoup object with the same TreeBuilder,
  303. but not associated with any markup.
  304. This is the first step of the deepcopy process.
  305. """
  306. clone = type(self)("", None, self.builder)
  307. # Keep track of the encoding of the original document,
  308. # since we won't be parsing it again.
  309. clone.original_encoding = self.original_encoding
  310. return clone
  311. def __getstate__(self):
  312. # Frequently a tree builder can't be pickled.
  313. d = dict(self.__dict__)
  314. if 'builder' in d and d['builder'] is not None and not self.builder.picklable:
  315. d['builder'] = type(self.builder)
  316. # Store the contents as a Unicode string.
  317. d['contents'] = []
  318. d['markup'] = self.decode()
  319. # If _most_recent_element is present, it's a Tag object left
  320. # over from initial parse. It might not be picklable and we
  321. # don't need it.
  322. if '_most_recent_element' in d:
  323. del d['_most_recent_element']
  324. return d
  325. def __setstate__(self, state):
  326. # If necessary, restore the TreeBuilder by looking it up.
  327. self.__dict__ = state
  328. if isinstance(self.builder, type):
  329. self.builder = self.builder()
  330. elif not self.builder:
  331. # We don't know which builder was used to build this
  332. # parse tree, so use a default we know is always available.
  333. self.builder = HTMLParserTreeBuilder()
  334. self.builder.soup = self
  335. self.reset()
  336. self._feed()
  337. return state
  338. @classmethod
  339. def _decode_markup(cls, markup):
  340. """Ensure `markup` is bytes so it's safe to send into warnings.warn.
  341. TODO: warnings.warn had this problem back in 2010 but it might not
  342. anymore.
  343. """
  344. if isinstance(markup, bytes):
  345. decoded = markup.decode('utf-8', 'replace')
  346. else:
  347. decoded = markup
  348. return decoded
  349. @classmethod
  350. def _markup_is_url(cls, markup):
  351. """Error-handling method to raise a warning if incoming markup looks
  352. like a URL.
  353. :param markup: A string.
  354. :return: Whether or not the markup resembles a URL
  355. closely enough to justify a warning.
  356. """
  357. if isinstance(markup, bytes):
  358. space = b' '
  359. cant_start_with = (b"http:", b"https:")
  360. elif isinstance(markup, str):
  361. space = ' '
  362. cant_start_with = ("http:", "https:")
  363. else:
  364. return False
  365. if any(markup.startswith(prefix) for prefix in cant_start_with):
  366. if not space in markup:
  367. warnings.warn(
  368. 'The input looks more like a URL than markup. You may want to use'
  369. ' an HTTP client like requests to get the document behind'
  370. ' the URL, and feed that document to Beautiful Soup.',
  371. MarkupResemblesLocatorWarning,
  372. stacklevel=3
  373. )
  374. return True
  375. return False
  376. @classmethod
  377. def _markup_resembles_filename(cls, markup):
  378. """Error-handling method to raise a warning if incoming markup
  379. resembles a filename.
  380. :param markup: A bytestring or string.
  381. :return: Whether or not the markup resembles a filename
  382. closely enough to justify a warning.
  383. """
  384. path_characters = '/\\'
  385. extensions = ['.html', '.htm', '.xml', '.xhtml', '.txt']
  386. if isinstance(markup, bytes):
  387. path_characters = path_characters.encode("utf8")
  388. extensions = [x.encode('utf8') for x in extensions]
  389. filelike = False
  390. if any(x in markup for x in path_characters):
  391. filelike = True
  392. else:
  393. lower = markup.lower()
  394. if any(lower.endswith(ext) for ext in extensions):
  395. filelike = True
  396. if filelike:
  397. warnings.warn(
  398. 'The input looks more like a filename than markup. You may'
  399. ' want to open this file and pass the filehandle into'
  400. ' Beautiful Soup.',
  401. MarkupResemblesLocatorWarning, stacklevel=3
  402. )
  403. return True
  404. return False
  405. def _feed(self):
  406. """Internal method that parses previously set markup, creating a large
  407. number of Tag and NavigableString objects.
  408. """
  409. # Convert the document to Unicode.
  410. self.builder.reset()
  411. self.builder.feed(self.markup)
  412. # Close out any unfinished strings and close all the open tags.
  413. self.endData()
  414. while self.currentTag.name != self.ROOT_TAG_NAME:
  415. self.popTag()
  416. def reset(self):
  417. """Reset this object to a state as though it had never parsed any
  418. markup.
  419. """
  420. Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME)
  421. self.hidden = 1
  422. self.builder.reset()
  423. self.current_data = []
  424. self.currentTag = None
  425. self.tagStack = []
  426. self.open_tag_counter = Counter()
  427. self.preserve_whitespace_tag_stack = []
  428. self.string_container_stack = []
  429. self._most_recent_element = None
  430. self.pushTag(self)
  431. def new_tag(self, name, namespace=None, nsprefix=None, attrs={},
  432. sourceline=None, sourcepos=None, **kwattrs):
  433. """Create a new Tag associated with this BeautifulSoup object.
  434. :param name: The name of the new Tag.
  435. :param namespace: The URI of the new Tag's XML namespace, if any.
  436. :param prefix: The prefix for the new Tag's XML namespace, if any.
  437. :param attrs: A dictionary of this Tag's attribute values; can
  438. be used instead of `kwattrs` for attributes like 'class'
  439. that are reserved words in Python.
  440. :param sourceline: The line number where this tag was
  441. (purportedly) found in its source document.
  442. :param sourcepos: The character position within `sourceline` where this
  443. tag was (purportedly) found.
  444. :param kwattrs: Keyword arguments for the new Tag's attribute values.
  445. """
  446. kwattrs.update(attrs)
  447. return self.element_classes.get(Tag, Tag)(
  448. None, self.builder, name, namespace, nsprefix, kwattrs,
  449. sourceline=sourceline, sourcepos=sourcepos
  450. )
  451. def string_container(self, base_class=None):
  452. container = base_class or NavigableString
  453. # There may be a general override of NavigableString.
  454. container = self.element_classes.get(
  455. container, container
  456. )
  457. # On top of that, we may be inside a tag that needs a special
  458. # container class.
  459. if self.string_container_stack and container is NavigableString:
  460. container = self.builder.string_containers.get(
  461. self.string_container_stack[-1].name, container
  462. )
  463. return container
  464. def new_string(self, s, subclass=None):
  465. """Create a new NavigableString associated with this BeautifulSoup
  466. object.
  467. """
  468. container = self.string_container(subclass)
  469. return container(s)
  470. def insert_before(self, *args):
  471. """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement
  472. it because there is nothing before or after it in the parse tree.
  473. """
  474. raise NotImplementedError("BeautifulSoup objects don't support insert_before().")
  475. def insert_after(self, *args):
  476. """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement
  477. it because there is nothing before or after it in the parse tree.
  478. """
  479. raise NotImplementedError("BeautifulSoup objects don't support insert_after().")
  480. def popTag(self):
  481. """Internal method called by _popToTag when a tag is closed."""
  482. tag = self.tagStack.pop()
  483. if tag.name in self.open_tag_counter:
  484. self.open_tag_counter[tag.name] -= 1
  485. if self.preserve_whitespace_tag_stack and tag == self.preserve_whitespace_tag_stack[-1]:
  486. self.preserve_whitespace_tag_stack.pop()
  487. if self.string_container_stack and tag == self.string_container_stack[-1]:
  488. self.string_container_stack.pop()
  489. #print("Pop", tag.name)
  490. if self.tagStack:
  491. self.currentTag = self.tagStack[-1]
  492. return self.currentTag
  493. def pushTag(self, tag):
  494. """Internal method called by handle_starttag when a tag is opened."""
  495. #print("Push", tag.name)
  496. if self.currentTag is not None:
  497. self.currentTag.contents.append(tag)
  498. self.tagStack.append(tag)
  499. self.currentTag = self.tagStack[-1]
  500. if tag.name != self.ROOT_TAG_NAME:
  501. self.open_tag_counter[tag.name] += 1
  502. if tag.name in self.builder.preserve_whitespace_tags:
  503. self.preserve_whitespace_tag_stack.append(tag)
  504. if tag.name in self.builder.string_containers:
  505. self.string_container_stack.append(tag)
  506. def endData(self, containerClass=None):
  507. """Method called by the TreeBuilder when the end of a data segment
  508. occurs.
  509. """
  510. if self.current_data:
  511. current_data = ''.join(self.current_data)
  512. # If whitespace is not preserved, and this string contains
  513. # nothing but ASCII spaces, replace it with a single space
  514. # or newline.
  515. if not self.preserve_whitespace_tag_stack:
  516. strippable = True
  517. for i in current_data:
  518. if i not in self.ASCII_SPACES:
  519. strippable = False
  520. break
  521. if strippable:
  522. if '\n' in current_data:
  523. current_data = '\n'
  524. else:
  525. current_data = ' '
  526. # Reset the data collector.
  527. self.current_data = []
  528. # Should we add this string to the tree at all?
  529. if self.parse_only and len(self.tagStack) <= 1 and \
  530. (not self.parse_only.text or \
  531. not self.parse_only.search(current_data)):
  532. return
  533. containerClass = self.string_container(containerClass)
  534. o = containerClass(current_data)
  535. self.object_was_parsed(o)
  536. def object_was_parsed(self, o, parent=None, most_recent_element=None):
  537. """Method called by the TreeBuilder to integrate an object into the parse tree."""
  538. if parent is None:
  539. parent = self.currentTag
  540. if most_recent_element is not None:
  541. previous_element = most_recent_element
  542. else:
  543. previous_element = self._most_recent_element
  544. next_element = previous_sibling = next_sibling = None
  545. if isinstance(o, Tag):
  546. next_element = o.next_element
  547. next_sibling = o.next_sibling
  548. previous_sibling = o.previous_sibling
  549. if previous_element is None:
  550. previous_element = o.previous_element
  551. fix = parent.next_element is not None
  552. o.setup(parent, previous_element, next_element, previous_sibling, next_sibling)
  553. self._most_recent_element = o
  554. parent.contents.append(o)
  555. # Check if we are inserting into an already parsed node.
  556. if fix:
  557. self._linkage_fixer(parent)
  558. def _linkage_fixer(self, el):
  559. """Make sure linkage of this fragment is sound."""
  560. first = el.contents[0]
  561. child = el.contents[-1]
  562. descendant = child
  563. if child is first and el.parent is not None:
  564. # Parent should be linked to first child
  565. el.next_element = child
  566. # We are no longer linked to whatever this element is
  567. prev_el = child.previous_element
  568. if prev_el is not None and prev_el is not el:
  569. prev_el.next_element = None
  570. # First child should be linked to the parent, and no previous siblings.
  571. child.previous_element = el
  572. child.previous_sibling = None
  573. # We have no sibling as we've been appended as the last.
  574. child.next_sibling = None
  575. # This index is a tag, dig deeper for a "last descendant"
  576. if isinstance(child, Tag) and child.contents:
  577. descendant = child._last_descendant(False)
  578. # As the final step, link last descendant. It should be linked
  579. # to the parent's next sibling (if found), else walk up the chain
  580. # and find a parent with a sibling. It should have no next sibling.
  581. descendant.next_element = None
  582. descendant.next_sibling = None
  583. target = el
  584. while True:
  585. if target is None:
  586. break
  587. elif target.next_sibling is not None:
  588. descendant.next_element = target.next_sibling
  589. target.next_sibling.previous_element = child
  590. break
  591. target = target.parent
  592. def _popToTag(self, name, nsprefix=None, inclusivePop=True):
  593. """Pops the tag stack up to and including the most recent
  594. instance of the given tag.
  595. If there are no open tags with the given name, nothing will be
  596. popped.
  597. :param name: Pop up to the most recent tag with this name.
  598. :param nsprefix: The namespace prefix that goes with `name`.
  599. :param inclusivePop: It this is false, pops the tag stack up
  600. to but *not* including the most recent instqance of the
  601. given tag.
  602. """
  603. #print("Popping to %s" % name)
  604. if name == self.ROOT_TAG_NAME:
  605. # The BeautifulSoup object itself can never be popped.
  606. return
  607. most_recently_popped = None
  608. stack_size = len(self.tagStack)
  609. for i in range(stack_size - 1, 0, -1):
  610. if not self.open_tag_counter.get(name):
  611. break
  612. t = self.tagStack[i]
  613. if (name == t.name and nsprefix == t.prefix):
  614. if inclusivePop:
  615. most_recently_popped = self.popTag()
  616. break
  617. most_recently_popped = self.popTag()
  618. return most_recently_popped
  619. def handle_starttag(self, name, namespace, nsprefix, attrs, sourceline=None,
  620. sourcepos=None, namespaces=None):
  621. """Called by the tree builder when a new tag is encountered.
  622. :param name: Name of the tag.
  623. :param nsprefix: Namespace prefix for the tag.
  624. :param attrs: A dictionary of attribute values.
  625. :param sourceline: The line number where this tag was found in its
  626. source document.
  627. :param sourcepos: The character position within `sourceline` where this
  628. tag was found.
  629. :param namespaces: A dictionary of all namespace prefix mappings
  630. currently in scope in the document.
  631. If this method returns None, the tag was rejected by an active
  632. SoupStrainer. You should proceed as if the tag had not occurred
  633. in the document. For instance, if this was a self-closing tag,
  634. don't call handle_endtag.
  635. """
  636. # print("Start tag %s: %s" % (name, attrs))
  637. self.endData()
  638. if (self.parse_only and len(self.tagStack) <= 1
  639. and (self.parse_only.text
  640. or not self.parse_only.search_tag(name, attrs))):
  641. return None
  642. tag = self.element_classes.get(Tag, Tag)(
  643. self, self.builder, name, namespace, nsprefix, attrs,
  644. self.currentTag, self._most_recent_element,
  645. sourceline=sourceline, sourcepos=sourcepos,
  646. namespaces=namespaces
  647. )
  648. if tag is None:
  649. return tag
  650. if self._most_recent_element is not None:
  651. self._most_recent_element.next_element = tag
  652. self._most_recent_element = tag
  653. self.pushTag(tag)
  654. return tag
  655. def handle_endtag(self, name, nsprefix=None):
  656. """Called by the tree builder when an ending tag is encountered.
  657. :param name: Name of the tag.
  658. :param nsprefix: Namespace prefix for the tag.
  659. """
  660. #print("End tag: " + name)
  661. self.endData()
  662. self._popToTag(name, nsprefix)
  663. def handle_data(self, data):
  664. """Called by the tree builder when a chunk of textual data is encountered."""
  665. self.current_data.append(data)
  666. def decode(self, pretty_print=False,
  667. eventual_encoding=DEFAULT_OUTPUT_ENCODING,
  668. formatter="minimal", iterator=None):
  669. """Returns a string or Unicode representation of the parse tree
  670. as an HTML or XML document.
  671. :param pretty_print: If this is True, indentation will be used to
  672. make the document more readable.
  673. :param eventual_encoding: The encoding of the final document.
  674. If this is None, the document will be a Unicode string.
  675. """
  676. if self.is_xml:
  677. # Print the XML declaration
  678. encoding_part = ''
  679. if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS:
  680. # This is a special Python encoding; it can't actually
  681. # go into an XML document because it means nothing
  682. # outside of Python.
  683. eventual_encoding = None
  684. if eventual_encoding != None:
  685. encoding_part = ' encoding="%s"' % eventual_encoding
  686. prefix = '<?xml version="1.0"%s?>\n' % encoding_part
  687. else:
  688. prefix = ''
  689. if not pretty_print:
  690. indent_level = None
  691. else:
  692. indent_level = 0
  693. return prefix + super(BeautifulSoup, self).decode(
  694. indent_level, eventual_encoding, formatter, iterator)
  695. # Aliases to make it easier to get started quickly, e.g. 'from bs4 import _soup'
  696. _s = BeautifulSoup
  697. _soup = BeautifulSoup
  698. class BeautifulStoneSoup(BeautifulSoup):
  699. """Deprecated interface to an XML parser."""
  700. def __init__(self, *args, **kwargs):
  701. kwargs['features'] = 'xml'
  702. warnings.warn(
  703. 'The BeautifulStoneSoup class is deprecated. Instead of using '
  704. 'it, pass features="xml" into the BeautifulSoup constructor.',
  705. DeprecationWarning, stacklevel=2
  706. )
  707. super(BeautifulStoneSoup, self).__init__(*args, **kwargs)
  708. class StopParsing(Exception):
  709. """Exception raised by a TreeBuilder if it's unable to continue parsing."""
  710. pass
  711. class FeatureNotFound(ValueError):
  712. """Exception raised by the BeautifulSoup constructor if no parser with the
  713. requested features is found.
  714. """
  715. pass
  716. #If this file is run as a script, act as an HTML pretty-printer.
  717. if __name__ == '__main__':
  718. soup = BeautifulSoup(sys.stdin)
  719. print((soup.prettify()))