_html5lib.py 10 KB

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