__init__.py 32 KB

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