_html5lib.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. __all__ = [
  2. 'HTML5TreeBuilder',
  3. ]
  4. from pdb import set_trace
  5. import warnings
  6. from bs4.builder import (
  7. PERMISSIVE,
  8. HTML,
  9. HTML_5,
  10. HTMLTreeBuilder,
  11. )
  12. from bs4.element import (
  13. NamespacedAttribute,
  14. whitespace_re,
  15. )
  16. import html5lib
  17. try:
  18. # html5lib >= 0.99999999/1.0b9
  19. from html5lib.treebuilders import base as treebuildersbase
  20. except ImportError:
  21. # html5lib <= 0.9999999/1.0b8
  22. from html5lib.treebuilders import _base as treebuildersbase
  23. from html5lib.constants import namespaces
  24. from bs4.element import (
  25. Comment,
  26. Doctype,
  27. NavigableString,
  28. Tag,
  29. )
  30. class HTML5TreeBuilder(HTMLTreeBuilder):
  31. """Use html5lib to build a tree."""
  32. NAME = "html5lib"
  33. features = [NAME, PERMISSIVE, HTML_5, HTML]
  34. def prepare_markup(self, markup, user_specified_encoding,
  35. document_declared_encoding=None, exclude_encodings=None):
  36. # Store the user-specified encoding for use later on.
  37. self.user_specified_encoding = user_specified_encoding
  38. # document_declared_encoding and exclude_encodings aren't used
  39. # ATM because the html5lib TreeBuilder doesn't use
  40. # UnicodeDammit.
  41. if exclude_encodings:
  42. warnings.warn("You provided a value for exclude_encoding, but the html5lib tree builder doesn't support exclude_encoding.")
  43. yield (markup, None, None, False)
  44. # These methods are defined by Beautiful Soup.
  45. def feed(self, markup):
  46. if self.soup.parse_only is not None:
  47. warnings.warn("You provided a value for parse_only, but the html5lib tree builder doesn't support parse_only. The entire document will be parsed.")
  48. parser = html5lib.HTMLParser(tree=self.create_treebuilder)
  49. doc = parser.parse(markup, encoding=self.user_specified_encoding)
  50. # Set the character encoding detected by the tokenizer.
  51. if isinstance(markup, str):
  52. # We need to special-case this because html5lib sets
  53. # charEncoding to UTF-8 if it gets Unicode input.
  54. doc.original_encoding = None
  55. else:
  56. doc.original_encoding = parser.tokenizer.stream.charEncoding[0]
  57. def create_treebuilder(self, namespaceHTMLElements):
  58. self.underlying_builder = TreeBuilderForHtml5lib(
  59. self.soup, namespaceHTMLElements)
  60. return self.underlying_builder
  61. def test_fragment_to_document(self, fragment):
  62. """See `TreeBuilder`."""
  63. return '<html><head></head><body>%s</body></html>' % fragment
  64. class TreeBuilderForHtml5lib(treebuildersbase.TreeBuilder):
  65. def __init__(self, soup, namespaceHTMLElements):
  66. self.soup = soup
  67. super(TreeBuilderForHtml5lib, self).__init__(namespaceHTMLElements)
  68. def documentClass(self):
  69. self.soup.reset()
  70. return Element(self.soup, self.soup, None)
  71. def insertDoctype(self, token):
  72. name = token["name"]
  73. publicId = token["publicId"]
  74. systemId = token["systemId"]
  75. doctype = Doctype.for_name_and_ids(name, publicId, systemId)
  76. self.soup.object_was_parsed(doctype)
  77. def elementClass(self, name, namespace):
  78. tag = self.soup.new_tag(name, namespace)
  79. return Element(tag, self.soup, namespace)
  80. def commentClass(self, data):
  81. return TextNode(Comment(data), self.soup)
  82. def fragmentClass(self):
  83. self.soup = BeautifulSoup("")
  84. self.soup.name = "[document_fragment]"
  85. return Element(self.soup, self.soup, None)
  86. def appendChild(self, node):
  87. # XXX This code is not covered by the BS4 tests.
  88. self.soup.append(node.element)
  89. def getDocument(self):
  90. return self.soup
  91. def getFragment(self):
  92. return treebuildersbase.TreeBuilder.getFragment(self).element
  93. class AttrList(object):
  94. def __init__(self, element):
  95. self.element = element
  96. self.attrs = dict(self.element.attrs)
  97. def __iter__(self):
  98. return list(self.attrs.items()).__iter__()
  99. def __setitem__(self, name, value):
  100. # If this attribute is a multi-valued attribute for this element,
  101. # turn its value into a list.
  102. list_attr = HTML5TreeBuilder.cdata_list_attributes
  103. if (name in list_attr['*']
  104. or (self.element.name in list_attr
  105. and name in list_attr[self.element.name])):
  106. # A node that is being cloned may have already undergone
  107. # this procedure.
  108. if not isinstance(value, list):
  109. value = whitespace_re.split(value)
  110. self.element[name] = value
  111. def items(self):
  112. return list(self.attrs.items())
  113. def keys(self):
  114. return list(self.attrs.keys())
  115. def __len__(self):
  116. return len(self.attrs)
  117. def __getitem__(self, name):
  118. return self.attrs[name]
  119. def __contains__(self, name):
  120. return name in list(self.attrs.keys())
  121. class Element(treebuildersbase.Node):
  122. def __init__(self, element, soup, namespace):
  123. treebuildersbase.Node.__init__(self, element.name)
  124. self.element = element
  125. self.soup = soup
  126. self.namespace = namespace
  127. def appendChild(self, node):
  128. string_child = child = None
  129. if isinstance(node, str):
  130. # Some other piece of code decided to pass in a string
  131. # instead of creating a TextElement object to contain the
  132. # string.
  133. string_child = child = node
  134. elif isinstance(node, Tag):
  135. # Some other piece of code decided to pass in a Tag
  136. # instead of creating an Element object to contain the
  137. # Tag.
  138. child = node
  139. elif node.element.__class__ == NavigableString:
  140. string_child = child = node.element
  141. else:
  142. child = node.element
  143. if not isinstance(child, str) and child.parent is not None:
  144. node.element.extract()
  145. if (string_child and self.element.contents
  146. and self.element.contents[-1].__class__ == NavigableString):
  147. # We are appending a string onto another string.
  148. # TODO This has O(n^2) performance, for input like
  149. # "a</a>a</a>a</a>..."
  150. old_element = self.element.contents[-1]
  151. new_element = self.soup.new_string(old_element + string_child)
  152. old_element.replace_with(new_element)
  153. self.soup._most_recent_element = new_element
  154. else:
  155. if isinstance(node, str):
  156. # Create a brand new NavigableString from this string.
  157. child = self.soup.new_string(node)
  158. # Tell Beautiful Soup to act as if it parsed this element
  159. # immediately after the parent's last descendant. (Or
  160. # immediately after the parent, if it has no children.)
  161. if self.element.contents:
  162. most_recent_element = self.element._last_descendant(False)
  163. elif self.element.next_element is not None:
  164. # Something from further ahead in the parse tree is
  165. # being inserted into this earlier element. This is
  166. # very annoying because it means an expensive search
  167. # for the last element in the tree.
  168. most_recent_element = self.soup._last_descendant()
  169. else:
  170. most_recent_element = self.element
  171. self.soup.object_was_parsed(
  172. child, parent=self.element,
  173. most_recent_element=most_recent_element)
  174. def getAttributes(self):
  175. return AttrList(self.element)
  176. def setAttributes(self, attributes):
  177. if attributes is not None and len(attributes) > 0:
  178. converted_attributes = []
  179. for name, value in list(attributes.items()):
  180. if isinstance(name, tuple):
  181. new_name = NamespacedAttribute(*name)
  182. del attributes[name]
  183. attributes[new_name] = value
  184. self.soup.builder._replace_cdata_list_attribute_values(
  185. self.name, attributes)
  186. for name, value in list(attributes.items()):
  187. self.element[name] = value
  188. # The attributes may contain variables that need substitution.
  189. # Call set_up_substitutions manually.
  190. #
  191. # The Tag constructor called this method when the Tag was created,
  192. # but we just set/changed the attributes, so call it again.
  193. self.soup.builder.set_up_substitutions(self.element)
  194. attributes = property(getAttributes, setAttributes)
  195. def insertText(self, data, insertBefore=None):
  196. if insertBefore:
  197. text = TextNode(self.soup.new_string(data), self.soup)
  198. self.insertBefore(data, insertBefore)
  199. else:
  200. self.appendChild(data)
  201. def insertBefore(self, node, refNode):
  202. index = self.element.index(refNode.element)
  203. if (node.element.__class__ == NavigableString and self.element.contents
  204. and self.element.contents[index-1].__class__ == NavigableString):
  205. # (See comments in appendChild)
  206. old_node = self.element.contents[index-1]
  207. new_str = self.soup.new_string(old_node + node.element)
  208. old_node.replace_with(new_str)
  209. else:
  210. self.element.insert(index, node.element)
  211. node.parent = self
  212. def removeChild(self, node):
  213. node.element.extract()
  214. def reparentChildren(self, new_parent):
  215. """Move all of this tag's children into another tag."""
  216. # print "MOVE", self.element.contents
  217. # print "FROM", self.element
  218. # print "TO", new_parent.element
  219. element = self.element
  220. new_parent_element = new_parent.element
  221. # Determine what this tag's next_element will be once all the children
  222. # are removed.
  223. final_next_element = element.next_sibling
  224. new_parents_last_descendant = new_parent_element._last_descendant(False, False)
  225. if len(new_parent_element.contents) > 0:
  226. # The new parent already contains children. We will be
  227. # appending this tag's children to the end.
  228. new_parents_last_child = new_parent_element.contents[-1]
  229. new_parents_last_descendant_next_element = new_parents_last_descendant.next_element
  230. else:
  231. # The new parent contains no children.
  232. new_parents_last_child = None
  233. new_parents_last_descendant_next_element = new_parent_element.next_element
  234. to_append = element.contents
  235. append_after = new_parent_element.contents
  236. if len(to_append) > 0:
  237. # Set the first child's previous_element and previous_sibling
  238. # to elements within the new parent
  239. first_child = to_append[0]
  240. if new_parents_last_descendant:
  241. first_child.previous_element = new_parents_last_descendant
  242. else:
  243. first_child.previous_element = new_parent_element
  244. first_child.previous_sibling = new_parents_last_child
  245. if new_parents_last_descendant:
  246. new_parents_last_descendant.next_element = first_child
  247. else:
  248. new_parent_element.next_element = first_child
  249. if new_parents_last_child:
  250. new_parents_last_child.next_sibling = first_child
  251. # Fix the last child's next_element and next_sibling
  252. last_child = to_append[-1]
  253. last_child.next_element = new_parents_last_descendant_next_element
  254. if new_parents_last_descendant_next_element:
  255. new_parents_last_descendant_next_element.previous_element = last_child
  256. last_child.next_sibling = None
  257. for child in to_append:
  258. child.parent = new_parent_element
  259. new_parent_element.contents.append(child)
  260. # Now that this element has no children, change its .next_element.
  261. element.contents = []
  262. element.next_element = final_next_element
  263. # print "DONE WITH MOVE"
  264. # print "FROM", self.element
  265. # print "TO", new_parent_element
  266. def cloneNode(self):
  267. tag = self.soup.new_tag(self.element.name, self.namespace)
  268. node = Element(tag, self.soup, self.namespace)
  269. for key,value in self.attributes:
  270. node.attributes[key] = value
  271. return node
  272. def hasContent(self):
  273. return self.element.contents
  274. def getNameTuple(self):
  275. if self.namespace == None:
  276. return namespaces["html"], self.name
  277. else:
  278. return self.namespace, self.name
  279. nameTuple = property(getNameTuple)
  280. class TextNode(Element):
  281. def __init__(self, element, soup):
  282. treebuildersbase.Node.__init__(self, None)
  283. self.element = element
  284. self.soup = soup
  285. def cloneNode(self):
  286. raise NotImplementedError