__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. from collections import defaultdict
  2. import itertools
  3. import sys
  4. from bs4.element import (
  5. CharsetMetaAttributeValue,
  6. ContentMetaAttributeValue,
  7. whitespace_re
  8. )
  9. __all__ = [
  10. 'HTMLTreeBuilder',
  11. 'SAXTreeBuilder',
  12. 'TreeBuilder',
  13. 'TreeBuilderRegistry',
  14. ]
  15. # Some useful features for a TreeBuilder to have.
  16. FAST = 'fast'
  17. PERMISSIVE = 'permissive'
  18. STRICT = 'strict'
  19. XML = 'xml'
  20. HTML = 'html'
  21. HTML_5 = 'html5'
  22. class TreeBuilderRegistry(object):
  23. def __init__(self):
  24. self.builders_for_feature = defaultdict(list)
  25. self.builders = []
  26. def register(self, treebuilder_class):
  27. """Register a treebuilder based on its advertised features."""
  28. for feature in treebuilder_class.features:
  29. self.builders_for_feature[feature].insert(0, treebuilder_class)
  30. self.builders.insert(0, treebuilder_class)
  31. def lookup(self, *features):
  32. if len(self.builders) == 0:
  33. # There are no builders at all.
  34. return None
  35. if len(features) == 0:
  36. # They didn't ask for any features. Give them the most
  37. # recently registered builder.
  38. return self.builders[0]
  39. # Go down the list of features in order, and eliminate any builders
  40. # that don't match every feature.
  41. features = list(features)
  42. features.reverse()
  43. candidates = None
  44. candidate_set = None
  45. while len(features) > 0:
  46. feature = features.pop()
  47. we_have_the_feature = self.builders_for_feature.get(feature, [])
  48. if len(we_have_the_feature) > 0:
  49. if candidates is None:
  50. candidates = we_have_the_feature
  51. candidate_set = set(candidates)
  52. else:
  53. # Eliminate any candidates that don't have this feature.
  54. candidate_set = candidate_set.intersection(
  55. set(we_have_the_feature))
  56. # The only valid candidates are the ones in candidate_set.
  57. # Go through the original list of candidates and pick the first one
  58. # that's in candidate_set.
  59. if candidate_set is None:
  60. return None
  61. for candidate in candidates:
  62. if candidate in candidate_set:
  63. return candidate
  64. return None
  65. # The BeautifulSoup class will take feature lists from developers and use them
  66. # to look up builders in this registry.
  67. builder_registry = TreeBuilderRegistry()
  68. class TreeBuilder(object):
  69. """Turn a document into a Beautiful Soup object tree."""
  70. features = []
  71. is_xml = False
  72. preserve_whitespace_tags = set()
  73. empty_element_tags = None # A tag will be considered an empty-element
  74. # tag when and only when it has no contents.
  75. # A value for these tag/attribute combinations is a space- or
  76. # comma-separated list of CDATA, rather than a single CDATA.
  77. cdata_list_attributes = {}
  78. def __init__(self):
  79. self.soup = None
  80. def reset(self):
  81. pass
  82. def can_be_empty_element(self, tag_name):
  83. """Might a tag with this name be an empty-element tag?
  84. The final markup may or may not actually present this tag as
  85. self-closing.
  86. For instance: an HTMLBuilder does not consider a <p> tag to be
  87. an empty-element tag (it's not in
  88. HTMLBuilder.empty_element_tags). This means an empty <p> tag
  89. will be presented as "<p></p>", not "<p />".
  90. The default implementation has no opinion about which tags are
  91. empty-element tags, so a tag will be presented as an
  92. empty-element tag if and only if it has no contents.
  93. "<foo></foo>" will become "<foo />", and "<foo>bar</foo>" will
  94. be left alone.
  95. """
  96. if self.empty_element_tags is None:
  97. return True
  98. return tag_name in self.empty_element_tags
  99. def feed(self, markup):
  100. raise NotImplementedError()
  101. def prepare_markup(self, markup, user_specified_encoding=None,
  102. document_declared_encoding=None):
  103. return markup, None, None, False
  104. def test_fragment_to_document(self, fragment):
  105. """Wrap an HTML fragment to make it look like a document.
  106. Different parsers do this differently. For instance, lxml
  107. introduces an empty <head> tag, and html5lib
  108. doesn't. Abstracting this away lets us write simple tests
  109. which run HTML fragments through the parser and compare the
  110. results against other HTML fragments.
  111. This method should not be used outside of tests.
  112. """
  113. return fragment
  114. def set_up_substitutions(self, tag):
  115. return False
  116. def _replace_cdata_list_attribute_values(self, tag_name, attrs):
  117. """Replaces class="foo bar" with class=["foo", "bar"]
  118. Modifies its input in place.
  119. """
  120. if not attrs:
  121. return attrs
  122. if self.cdata_list_attributes:
  123. universal = self.cdata_list_attributes.get('*', [])
  124. tag_specific = self.cdata_list_attributes.get(
  125. tag_name.lower(), None)
  126. for attr in attrs.keys():
  127. if attr in universal or (tag_specific and attr in tag_specific):
  128. # We have a "class"-type attribute whose string
  129. # value is a whitespace-separated list of
  130. # values. Split it into a list.
  131. value = attrs[attr]
  132. if isinstance(value, basestring):
  133. values = whitespace_re.split(value)
  134. else:
  135. # html5lib sometimes calls setAttributes twice
  136. # for the same tag when rearranging the parse
  137. # tree. On the second call the attribute value
  138. # here is already a list. If this happens,
  139. # leave the value alone rather than trying to
  140. # split it again.
  141. values = value
  142. attrs[attr] = values
  143. return attrs
  144. class SAXTreeBuilder(TreeBuilder):
  145. """A Beautiful Soup treebuilder that listens for SAX events."""
  146. def feed(self, markup):
  147. raise NotImplementedError()
  148. def close(self):
  149. pass
  150. def startElement(self, name, attrs):
  151. attrs = dict((key[1], value) for key, value in list(attrs.items()))
  152. #print "Start %s, %r" % (name, attrs)
  153. self.soup.handle_starttag(name, attrs)
  154. def endElement(self, name):
  155. #print "End %s" % name
  156. self.soup.handle_endtag(name)
  157. def startElementNS(self, nsTuple, nodeName, attrs):
  158. # Throw away (ns, nodeName) for now.
  159. self.startElement(nodeName, attrs)
  160. def endElementNS(self, nsTuple, nodeName):
  161. # Throw away (ns, nodeName) for now.
  162. self.endElement(nodeName)
  163. #handler.endElementNS((ns, node.nodeName), node.nodeName)
  164. def startPrefixMapping(self, prefix, nodeValue):
  165. # Ignore the prefix for now.
  166. pass
  167. def endPrefixMapping(self, prefix):
  168. # Ignore the prefix for now.
  169. # handler.endPrefixMapping(prefix)
  170. pass
  171. def characters(self, content):
  172. self.soup.handle_data(content)
  173. def startDocument(self):
  174. pass
  175. def endDocument(self):
  176. pass
  177. class HTMLTreeBuilder(TreeBuilder):
  178. """This TreeBuilder knows facts about HTML.
  179. Such as which tags are empty-element tags.
  180. """
  181. preserve_whitespace_tags = set(['pre', 'textarea'])
  182. empty_element_tags = set(['br' , 'hr', 'input', 'img', 'meta',
  183. 'spacer', 'link', 'frame', 'base'])
  184. # The HTML standard defines these attributes as containing a
  185. # space-separated list of values, not a single value. That is,
  186. # class="foo bar" means that the 'class' attribute has two values,
  187. # 'foo' and 'bar', not the single value 'foo bar'. When we
  188. # encounter one of these attributes, we will parse its value into
  189. # a list of values if possible. Upon output, the list will be
  190. # converted back into a string.
  191. cdata_list_attributes = {
  192. "*" : ['class', 'accesskey', 'dropzone'],
  193. "a" : ['rel', 'rev'],
  194. "link" : ['rel', 'rev'],
  195. "td" : ["headers"],
  196. "th" : ["headers"],
  197. "td" : ["headers"],
  198. "form" : ["accept-charset"],
  199. "object" : ["archive"],
  200. # These are HTML5 specific, as are *.accesskey and *.dropzone above.
  201. "area" : ["rel"],
  202. "icon" : ["sizes"],
  203. "iframe" : ["sandbox"],
  204. "output" : ["for"],
  205. }
  206. def set_up_substitutions(self, tag):
  207. # We are only interested in <meta> tags
  208. if tag.name != 'meta':
  209. return False
  210. http_equiv = tag.get('http-equiv')
  211. content = tag.get('content')
  212. charset = tag.get('charset')
  213. # We are interested in <meta> tags that say what encoding the
  214. # document was originally in. This means HTML 5-style <meta>
  215. # tags that provide the "charset" attribute. It also means
  216. # HTML 4-style <meta> tags that provide the "content"
  217. # attribute and have "http-equiv" set to "content-type".
  218. #
  219. # In both cases we will replace the value of the appropriate
  220. # attribute with a standin object that can take on any
  221. # encoding.
  222. meta_encoding = None
  223. if charset is not None:
  224. # HTML 5 style:
  225. # <meta charset="utf8">
  226. meta_encoding = charset
  227. tag['charset'] = CharsetMetaAttributeValue(charset)
  228. elif (content is not None and http_equiv is not None
  229. and http_equiv.lower() == 'content-type'):
  230. # HTML 4 style:
  231. # <meta http-equiv="content-type" content="text/html; charset=utf8">
  232. tag['content'] = ContentMetaAttributeValue(content)
  233. return (meta_encoding is not None)
  234. def register_treebuilders_from(module):
  235. """Copy TreeBuilders from the given module into this module."""
  236. # I'm fairly sure this is not the best way to do this.
  237. this_module = sys.modules['bs4.builder']
  238. for name in module.__all__:
  239. obj = getattr(module, name)
  240. if issubclass(obj, TreeBuilder):
  241. setattr(this_module, name, obj)
  242. this_module.__all__.append(name)
  243. # Register the builder while we're at it.
  244. this_module.builder_registry.register(obj)
  245. class ParserRejectedMarkup(Exception):
  246. pass
  247. # Builders are registered in reverse order of priority, so that custom
  248. # builder registrations will take precedence. In general, we want lxml
  249. # to take precedence over html5lib, because it's faster. And we only
  250. # want to use HTMLParser as a last result.
  251. from . import _htmlparser
  252. register_treebuilders_from(_htmlparser)
  253. try:
  254. from . import _html5lib
  255. register_treebuilders_from(_html5lib)
  256. except ImportError:
  257. # They don't have html5lib installed.
  258. pass
  259. try:
  260. from . import _lxml
  261. register_treebuilders_from(_lxml)
  262. except ImportError:
  263. # They don't have lxml installed.
  264. pass