__init__.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. """Beautiful Soup
  2. Elixir and Tonic
  3. "The Screen-Scraper's Friend"
  4. http://www.crummy.com/software/BeautifulSoup/
  5. Beautiful Soup uses a pluggable XML or HTML parser to parse a
  6. (possibly invalid) document into a tree representation. Beautiful Soup
  7. provides provides methods and Pythonic idioms that make it easy to
  8. navigate, search, and modify the parse tree.
  9. Beautiful Soup works with Python 2.6 and up. It works better if lxml
  10. and/or html5lib is installed.
  11. For more than you ever wanted to know about Beautiful Soup, see the
  12. documentation:
  13. http://www.crummy.com/software/BeautifulSoup/bs4/doc/
  14. """
  15. __author__ = "Leonard Richardson (leonardr@segfault.org)"
  16. __version__ = "4.4.1"
  17. __copyright__ = "Copyright (c) 2004-2015 Leonard Richardson"
  18. __license__ = "MIT"
  19. __all__ = ['BeautifulSoup']
  20. import os
  21. import re
  22. import warnings
  23. from .builder import builder_registry, ParserRejectedMarkup
  24. from .dammit import UnicodeDammit
  25. from .element import (
  26. CData,
  27. Comment,
  28. DEFAULT_OUTPUT_ENCODING,
  29. Declaration,
  30. Doctype,
  31. NavigableString,
  32. PageElement,
  33. ProcessingInstruction,
  34. ResultSet,
  35. SoupStrainer,
  36. Tag,
  37. )
  38. # The very first thing we do is give a useful error if someone is
  39. # running this code under Python 3 without converting it.
  40. 'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work.'!='You need to convert the code, either by installing it (`python setup.py install`) or by running 2to3 (`2to3 -w bs4`).'
  41. class BeautifulSoup(Tag):
  42. """
  43. This class defines the basic interface called by the tree builders.
  44. These methods will be called by the parser:
  45. reset()
  46. feed(markup)
  47. The tree builder may call these methods from its feed() implementation:
  48. handle_starttag(name, attrs) # See note about return value
  49. handle_endtag(name)
  50. handle_data(data) # Appends to the current data node
  51. endData(containerClass=NavigableString) # Ends the current data node
  52. No matter how complicated the underlying parser is, you should be
  53. able to build a tree using 'start tag' events, 'end tag' events,
  54. 'data' events, and "done with data" events.
  55. If you encounter an empty-element tag (aka a self-closing tag,
  56. like HTML's <br> tag), call handle_starttag and then
  57. handle_endtag.
  58. """
  59. ROOT_TAG_NAME = '[document]'
  60. # If the end-user gives no indication which tree builder they
  61. # want, look for one with these features.
  62. DEFAULT_BUILDER_FEATURES = ['html', 'fast']
  63. ASCII_SPACES = '\x20\x0a\x09\x0c\x0d'
  64. 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\nTo get rid of this warning, change this:\n\n BeautifulSoup([your markup])\n\nto this:\n\n BeautifulSoup([your markup], \"%(parser)s\")\n"
  65. def __init__(self, markup="", features=None, builder=None,
  66. parse_only=None, from_encoding=None, exclude_encodings=None,
  67. **kwargs):
  68. """The Soup object is initialized as the 'root tag', and the
  69. provided markup (which can be a string or a file-like object)
  70. is fed into the underlying parser."""
  71. if 'convertEntities' in kwargs:
  72. warnings.warn(
  73. "BS4 does not respect the convertEntities argument to the "
  74. "BeautifulSoup constructor. Entities are always converted "
  75. "to Unicode characters.")
  76. if 'markupMassage' in kwargs:
  77. del kwargs['markupMassage']
  78. warnings.warn(
  79. "BS4 does not respect the markupMassage argument to the "
  80. "BeautifulSoup constructor. The tree builder is responsible "
  81. "for any necessary markup massage.")
  82. if 'smartQuotesTo' in kwargs:
  83. del kwargs['smartQuotesTo']
  84. warnings.warn(
  85. "BS4 does not respect the smartQuotesTo argument to the "
  86. "BeautifulSoup constructor. Smart quotes are always converted "
  87. "to Unicode characters.")
  88. if 'selfClosingTags' in kwargs:
  89. del kwargs['selfClosingTags']
  90. warnings.warn(
  91. "BS4 does not respect the selfClosingTags argument to the "
  92. "BeautifulSoup constructor. The tree builder is responsible "
  93. "for understanding self-closing tags.")
  94. if 'isHTML' in kwargs:
  95. del kwargs['isHTML']
  96. warnings.warn(
  97. "BS4 does not respect the isHTML argument to the "
  98. "BeautifulSoup constructor. Suggest you use "
  99. "features='lxml' for HTML and features='lxml-xml' for "
  100. "XML.")
  101. def deprecated_argument(old_name, new_name):
  102. if old_name in kwargs:
  103. warnings.warn(
  104. 'The "%s" argument to the BeautifulSoup constructor '
  105. 'has been renamed to "%s."' % (old_name, new_name))
  106. value = kwargs[old_name]
  107. del kwargs[old_name]
  108. return value
  109. return None
  110. parse_only = parse_only or deprecated_argument(
  111. "parseOnlyThese", "parse_only")
  112. from_encoding = from_encoding or deprecated_argument(
  113. "fromEncoding", "from_encoding")
  114. if len(kwargs) > 0:
  115. arg = list(kwargs.keys()).pop()
  116. raise TypeError(
  117. "__init__() got an unexpected keyword argument '%s'" % arg)
  118. if builder is None:
  119. original_features = features
  120. if isinstance(features, str):
  121. features = [features]
  122. if features is None or len(features) == 0:
  123. features = self.DEFAULT_BUILDER_FEATURES
  124. builder_class = builder_registry.lookup(*features)
  125. if builder_class is None:
  126. raise FeatureNotFound(
  127. "Couldn't find a tree builder with the features you "
  128. "requested: %s. Do you need to install a parser library?"
  129. % ",".join(features))
  130. builder = builder_class()
  131. if not (original_features == builder.NAME or
  132. original_features in builder.ALTERNATE_NAMES):
  133. if builder.is_xml:
  134. markup_type = "XML"
  135. else:
  136. markup_type = "HTML"
  137. warnings.warn(self.NO_PARSER_SPECIFIED_WARNING % dict(
  138. parser=builder.NAME,
  139. markup_type=markup_type))
  140. self.builder = builder
  141. self.is_xml = builder.is_xml
  142. self.builder.soup = self
  143. self.parse_only = parse_only
  144. if hasattr(markup, 'read'): # It's a file-type object.
  145. markup = markup.read()
  146. elif len(markup) <= 256:
  147. # Print out warnings for a couple beginner problems
  148. # involving passing non-markup to Beautiful Soup.
  149. # Beautiful Soup will still parse the input as markup,
  150. # just in case that's what the user really wants.
  151. if (isinstance(markup, str)
  152. and not os.path.supports_unicode_filenames):
  153. possible_filename = markup.encode("utf8")
  154. else:
  155. possible_filename = markup
  156. is_file = False
  157. try:
  158. is_file = os.path.exists(possible_filename)
  159. except Exception as e:
  160. # This is almost certainly a problem involving
  161. # characters not valid in filenames on this
  162. # system. Just let it go.
  163. pass
  164. if is_file:
  165. if isinstance(markup, str):
  166. markup = markup.encode("utf8")
  167. warnings.warn(
  168. '"%s" looks like a filename, not markup. You should probably open this file and pass the filehandle into Beautiful Soup.' % markup)
  169. if markup[:5] == "http:" or markup[:6] == "https:":
  170. # TODO: This is ugly but I couldn't get it to work in
  171. # Python 3 otherwise.
  172. if ((isinstance(markup, bytes) and not b' ' in markup)
  173. or (isinstance(markup, str) and not ' ' in markup)):
  174. if isinstance(markup, str):
  175. markup = markup.encode("utf8")
  176. warnings.warn(
  177. '"%s" looks like a URL. Beautiful Soup is not an HTTP client. You should probably use an HTTP client to get the document behind the URL, and feed that document to Beautiful Soup.' % markup)
  178. for (self.markup, self.original_encoding, self.declared_html_encoding,
  179. self.contains_replacement_characters) in (
  180. self.builder.prepare_markup(
  181. markup, from_encoding, exclude_encodings=exclude_encodings)):
  182. self.reset()
  183. try:
  184. self._feed()
  185. break
  186. except ParserRejectedMarkup:
  187. pass
  188. # Clear out the markup and remove the builder's circular
  189. # reference to this object.
  190. self.markup = None
  191. self.builder.soup = None
  192. def __copy__(self):
  193. return type(self)(self.encode(), builder=self.builder)
  194. def __getstate__(self):
  195. # Frequently a tree builder can't be pickled.
  196. d = dict(self.__dict__)
  197. if 'builder' in d and not self.builder.picklable:
  198. del d['builder']
  199. return d
  200. def _feed(self):
  201. # Convert the document to Unicode.
  202. self.builder.reset()
  203. self.builder.feed(self.markup)
  204. # Close out any unfinished strings and close all the open tags.
  205. self.endData()
  206. while self.currentTag.name != self.ROOT_TAG_NAME:
  207. self.popTag()
  208. def reset(self):
  209. Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME)
  210. self.hidden = 1
  211. self.builder.reset()
  212. self.current_data = []
  213. self.currentTag = None
  214. self.tagStack = []
  215. self.preserve_whitespace_tag_stack = []
  216. self.pushTag(self)
  217. def new_tag(self, name, namespace=None, nsprefix=None, **attrs):
  218. """Create a new tag associated with this soup."""
  219. return Tag(None, self.builder, name, namespace, nsprefix, attrs)
  220. def new_string(self, s, subclass=NavigableString):
  221. """Create a new NavigableString associated with this soup."""
  222. return subclass(s)
  223. def insert_before(self, successor):
  224. raise NotImplementedError("BeautifulSoup objects don't support insert_before().")
  225. def insert_after(self, successor):
  226. raise NotImplementedError("BeautifulSoup objects don't support insert_after().")
  227. def popTag(self):
  228. tag = self.tagStack.pop()
  229. if self.preserve_whitespace_tag_stack and tag == self.preserve_whitespace_tag_stack[-1]:
  230. self.preserve_whitespace_tag_stack.pop()
  231. #print "Pop", tag.name
  232. if self.tagStack:
  233. self.currentTag = self.tagStack[-1]
  234. return self.currentTag
  235. def pushTag(self, tag):
  236. #print "Push", tag.name
  237. if self.currentTag:
  238. self.currentTag.contents.append(tag)
  239. self.tagStack.append(tag)
  240. self.currentTag = self.tagStack[-1]
  241. if tag.name in self.builder.preserve_whitespace_tags:
  242. self.preserve_whitespace_tag_stack.append(tag)
  243. def endData(self, containerClass=NavigableString):
  244. if self.current_data:
  245. current_data = ''.join(self.current_data)
  246. # If whitespace is not preserved, and this string contains
  247. # nothing but ASCII spaces, replace it with a single space
  248. # or newline.
  249. if not self.preserve_whitespace_tag_stack:
  250. strippable = True
  251. for i in current_data:
  252. if i not in self.ASCII_SPACES:
  253. strippable = False
  254. break
  255. if strippable:
  256. if '\n' in current_data:
  257. current_data = '\n'
  258. else:
  259. current_data = ' '
  260. # Reset the data collector.
  261. self.current_data = []
  262. # Should we add this string to the tree at all?
  263. if self.parse_only and len(self.tagStack) <= 1 and \
  264. (not self.parse_only.text or \
  265. not self.parse_only.search(current_data)):
  266. return
  267. o = containerClass(current_data)
  268. self.object_was_parsed(o)
  269. def object_was_parsed(self, o, parent=None, most_recent_element=None):
  270. """Add an object to the parse tree."""
  271. parent = parent or self.currentTag
  272. previous_element = most_recent_element or self._most_recent_element
  273. next_element = previous_sibling = next_sibling = None
  274. if isinstance(o, Tag):
  275. next_element = o.next_element
  276. next_sibling = o.next_sibling
  277. previous_sibling = o.previous_sibling
  278. if not previous_element:
  279. previous_element = o.previous_element
  280. o.setup(parent, previous_element, next_element, previous_sibling, next_sibling)
  281. self._most_recent_element = o
  282. parent.contents.append(o)
  283. if parent.next_sibling:
  284. # This node is being inserted into an element that has
  285. # already been parsed. Deal with any dangling references.
  286. index = parent.contents.index(o)
  287. if index == 0:
  288. previous_element = parent
  289. previous_sibling = None
  290. else:
  291. previous_element = previous_sibling = parent.contents[index-1]
  292. if index == len(parent.contents)-1:
  293. next_element = parent.next_sibling
  294. next_sibling = None
  295. else:
  296. next_element = next_sibling = parent.contents[index+1]
  297. o.previous_element = previous_element
  298. if previous_element:
  299. previous_element.next_element = o
  300. o.next_element = next_element
  301. if next_element:
  302. next_element.previous_element = o
  303. o.next_sibling = next_sibling
  304. if next_sibling:
  305. next_sibling.previous_sibling = o
  306. o.previous_sibling = previous_sibling
  307. if previous_sibling:
  308. previous_sibling.next_sibling = o
  309. def _popToTag(self, name, nsprefix=None, inclusivePop=True):
  310. """Pops the tag stack up to and including the most recent
  311. instance of the given tag. If inclusivePop is false, pops the tag
  312. stack up to but *not* including the most recent instqance of
  313. the given tag."""
  314. #print "Popping to %s" % name
  315. if name == self.ROOT_TAG_NAME:
  316. # The BeautifulSoup object itself can never be popped.
  317. return
  318. most_recently_popped = None
  319. stack_size = len(self.tagStack)
  320. for i in range(stack_size - 1, 0, -1):
  321. t = self.tagStack[i]
  322. if (name == t.name and nsprefix == t.prefix):
  323. if inclusivePop:
  324. most_recently_popped = self.popTag()
  325. break
  326. most_recently_popped = self.popTag()
  327. return most_recently_popped
  328. def handle_starttag(self, name, namespace, nsprefix, attrs):
  329. """Push a start tag on to the stack.
  330. If this method returns None, the tag was rejected by the
  331. SoupStrainer. You should proceed as if the tag had not occured
  332. in the document. For instance, if this was a self-closing tag,
  333. don't call handle_endtag.
  334. """
  335. # print "Start tag %s: %s" % (name, attrs)
  336. self.endData()
  337. if (self.parse_only and len(self.tagStack) <= 1
  338. and (self.parse_only.text
  339. or not self.parse_only.search_tag(name, attrs))):
  340. return None
  341. tag = Tag(self, self.builder, name, namespace, nsprefix, attrs,
  342. self.currentTag, self._most_recent_element)
  343. if tag is None:
  344. return tag
  345. if self._most_recent_element:
  346. self._most_recent_element.next_element = tag
  347. self._most_recent_element = tag
  348. self.pushTag(tag)
  349. return tag
  350. def handle_endtag(self, name, nsprefix=None):
  351. #print "End tag: " + name
  352. self.endData()
  353. self._popToTag(name, nsprefix)
  354. def handle_data(self, data):
  355. self.current_data.append(data)
  356. def decode(self, pretty_print=False,
  357. eventual_encoding=DEFAULT_OUTPUT_ENCODING,
  358. formatter="minimal"):
  359. """Returns a string or Unicode representation of this document.
  360. To get Unicode, pass None for encoding."""
  361. if self.is_xml:
  362. # Print the XML declaration
  363. encoding_part = ''
  364. if eventual_encoding is not None:
  365. encoding_part = ' encoding="%s"' % eventual_encoding
  366. prefix = '<?xml version="1.0"%s?>\n' % encoding_part
  367. else:
  368. prefix = ''
  369. if not pretty_print:
  370. indent_level = None
  371. else:
  372. indent_level = 0
  373. return prefix + super(BeautifulSoup, self).decode(
  374. indent_level, eventual_encoding, formatter)
  375. # Alias to make it easier to type import: 'from bs4 import _soup'
  376. _s = BeautifulSoup
  377. _soup = BeautifulSoup
  378. class BeautifulStoneSoup(BeautifulSoup):
  379. """Deprecated interface to an XML parser."""
  380. def __init__(self, *args, **kwargs):
  381. kwargs['features'] = 'xml'
  382. warnings.warn(
  383. 'The BeautifulStoneSoup class is deprecated. Instead of using '
  384. 'it, pass features="xml" into the BeautifulSoup constructor.')
  385. super(BeautifulStoneSoup, self).__init__(*args, **kwargs)
  386. class StopParsing(Exception):
  387. pass
  388. class FeatureNotFound(ValueError):
  389. pass
  390. #By default, act as an HTML pretty-printer.
  391. if __name__ == '__main__':
  392. import sys
  393. soup = BeautifulSoup(sys.stdin)
  394. print(soup.prettify())