_html5lib.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. # Use of this source code is governed by the MIT license.
  2. __license__ = "MIT"
  3. __all__ = [
  4. 'HTML5TreeBuilder',
  5. ]
  6. import warnings
  7. import re
  8. from bs4.builder import (
  9. DetectsXMLParsedAsHTML,
  10. PERMISSIVE,
  11. HTML,
  12. HTML_5,
  13. HTMLTreeBuilder,
  14. )
  15. from bs4.element import (
  16. NamespacedAttribute,
  17. nonwhitespace_re,
  18. )
  19. import html5lib
  20. from html5lib.constants import (
  21. namespaces,
  22. prefixes,
  23. )
  24. from bs4.element import (
  25. Comment,
  26. Doctype,
  27. NavigableString,
  28. Tag,
  29. )
  30. try:
  31. # Pre-0.99999999
  32. from html5lib.treebuilders import _base as treebuilder_base
  33. new_html5lib = False
  34. except ImportError as e:
  35. # 0.99999999 and up
  36. from html5lib.treebuilders import base as treebuilder_base
  37. new_html5lib = True
  38. class HTML5TreeBuilder(HTMLTreeBuilder):
  39. """Use html5lib to build a tree.
  40. Note that this TreeBuilder does not support some features common
  41. to HTML TreeBuilders. Some of these features could theoretically
  42. be implemented, but at the very least it's quite difficult,
  43. because html5lib moves the parse tree around as it's being built.
  44. * This TreeBuilder doesn't use different subclasses of NavigableString
  45. based on the name of the tag in which the string was found.
  46. * You can't use a SoupStrainer to parse only part of a document.
  47. """
  48. NAME = "html5lib"
  49. features = [NAME, PERMISSIVE, HTML_5, HTML]
  50. # html5lib can tell us which line number and position in the
  51. # original file is the source of an element.
  52. TRACKS_LINE_NUMBERS = True
  53. def prepare_markup(self, markup, user_specified_encoding,
  54. document_declared_encoding=None, exclude_encodings=None):
  55. # Store the user-specified encoding for use later on.
  56. self.user_specified_encoding = user_specified_encoding
  57. # document_declared_encoding and exclude_encodings aren't used
  58. # ATM because the html5lib TreeBuilder doesn't use
  59. # UnicodeDammit.
  60. if exclude_encodings:
  61. warnings.warn("You provided a value for exclude_encoding, but the html5lib tree builder doesn't support exclude_encoding.")
  62. # html5lib only parses HTML, so if it's given XML that's worth
  63. # noting.
  64. DetectsXMLParsedAsHTML.warn_if_markup_looks_like_xml(markup)
  65. yield (markup, None, None, False)
  66. # These methods are defined by Beautiful Soup.
  67. def feed(self, markup):
  68. if self.soup.parse_only is not None:
  69. 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.")
  70. parser = html5lib.HTMLParser(tree=self.create_treebuilder)
  71. self.underlying_builder.parser = parser
  72. extra_kwargs = dict()
  73. if not isinstance(markup, str):
  74. if new_html5lib:
  75. extra_kwargs['override_encoding'] = self.user_specified_encoding
  76. else:
  77. extra_kwargs['encoding'] = self.user_specified_encoding
  78. doc = parser.parse(markup, **extra_kwargs)
  79. # Set the character encoding detected by the tokenizer.
  80. if isinstance(markup, str):
  81. # We need to special-case this because html5lib sets
  82. # charEncoding to UTF-8 if it gets Unicode input.
  83. doc.original_encoding = None
  84. else:
  85. original_encoding = parser.tokenizer.stream.charEncoding[0]
  86. if not isinstance(original_encoding, str):
  87. # In 0.99999999 and up, the encoding is an html5lib
  88. # Encoding object. We want to use a string for compatibility
  89. # with other tree builders.
  90. original_encoding = original_encoding.name
  91. doc.original_encoding = original_encoding
  92. self.underlying_builder.parser = None
  93. def create_treebuilder(self, namespaceHTMLElements):
  94. self.underlying_builder = TreeBuilderForHtml5lib(
  95. namespaceHTMLElements, self.soup,
  96. store_line_numbers=self.store_line_numbers
  97. )
  98. return self.underlying_builder
  99. def test_fragment_to_document(self, fragment):
  100. """See `TreeBuilder`."""
  101. return '<html><head></head><body>%s</body></html>' % fragment
  102. class TreeBuilderForHtml5lib(treebuilder_base.TreeBuilder):
  103. def __init__(self, namespaceHTMLElements, soup=None,
  104. store_line_numbers=True, **kwargs):
  105. if soup:
  106. self.soup = soup
  107. else:
  108. from bs4 import BeautifulSoup
  109. # TODO: Why is the parser 'html.parser' here? To avoid an
  110. # infinite loop?
  111. self.soup = BeautifulSoup(
  112. "", "html.parser", store_line_numbers=store_line_numbers,
  113. **kwargs
  114. )
  115. # TODO: What are **kwargs exactly? Should they be passed in
  116. # here in addition to/instead of being passed to the BeautifulSoup
  117. # constructor?
  118. super(TreeBuilderForHtml5lib, self).__init__(namespaceHTMLElements)
  119. # This will be set later to an html5lib.html5parser.HTMLParser
  120. # object, which we can use to track the current line number.
  121. self.parser = None
  122. self.store_line_numbers = store_line_numbers
  123. def documentClass(self):
  124. self.soup.reset()
  125. return Element(self.soup, self.soup, None)
  126. def insertDoctype(self, token):
  127. name = token["name"]
  128. publicId = token["publicId"]
  129. systemId = token["systemId"]
  130. doctype = Doctype.for_name_and_ids(name, publicId, systemId)
  131. self.soup.object_was_parsed(doctype)
  132. def elementClass(self, name, namespace):
  133. kwargs = {}
  134. if self.parser and self.store_line_numbers:
  135. # This represents the point immediately after the end of the
  136. # tag. We don't know when the tag started, but we do know
  137. # where it ended -- the character just before this one.
  138. sourceline, sourcepos = self.parser.tokenizer.stream.position()
  139. kwargs['sourceline'] = sourceline
  140. kwargs['sourcepos'] = sourcepos-1
  141. tag = self.soup.new_tag(name, namespace, **kwargs)
  142. return Element(tag, self.soup, namespace)
  143. def commentClass(self, data):
  144. return TextNode(Comment(data), self.soup)
  145. def fragmentClass(self):
  146. from bs4 import BeautifulSoup
  147. # TODO: Why is the parser 'html.parser' here? To avoid an
  148. # infinite loop?
  149. self.soup = BeautifulSoup("", "html.parser")
  150. self.soup.name = "[document_fragment]"
  151. return Element(self.soup, self.soup, None)
  152. def appendChild(self, node):
  153. # XXX This code is not covered by the BS4 tests.
  154. self.soup.append(node.element)
  155. def getDocument(self):
  156. return self.soup
  157. def getFragment(self):
  158. return treebuilder_base.TreeBuilder.getFragment(self).element
  159. def testSerializer(self, element):
  160. from bs4 import BeautifulSoup
  161. rv = []
  162. doctype_re = re.compile(r'^(.*?)(?: PUBLIC "(.*?)"(?: "(.*?)")?| SYSTEM "(.*?)")?$')
  163. def serializeElement(element, indent=0):
  164. if isinstance(element, BeautifulSoup):
  165. pass
  166. if isinstance(element, Doctype):
  167. m = doctype_re.match(element)
  168. if m:
  169. name = m.group(1)
  170. if m.lastindex > 1:
  171. publicId = m.group(2) or ""
  172. systemId = m.group(3) or m.group(4) or ""
  173. rv.append("""|%s<!DOCTYPE %s "%s" "%s">""" %
  174. (' ' * indent, name, publicId, systemId))
  175. else:
  176. rv.append("|%s<!DOCTYPE %s>" % (' ' * indent, name))
  177. else:
  178. rv.append("|%s<!DOCTYPE >" % (' ' * indent,))
  179. elif isinstance(element, Comment):
  180. rv.append("|%s<!-- %s -->" % (' ' * indent, element))
  181. elif isinstance(element, NavigableString):
  182. rv.append("|%s\"%s\"" % (' ' * indent, element))
  183. else:
  184. if element.namespace:
  185. name = "%s %s" % (prefixes[element.namespace],
  186. element.name)
  187. else:
  188. name = element.name
  189. rv.append("|%s<%s>" % (' ' * indent, name))
  190. if element.attrs:
  191. attributes = []
  192. for name, value in list(element.attrs.items()):
  193. if isinstance(name, NamespacedAttribute):
  194. name = "%s %s" % (prefixes[name.namespace], name.name)
  195. if isinstance(value, list):
  196. value = " ".join(value)
  197. attributes.append((name, value))
  198. for name, value in sorted(attributes):
  199. rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value))
  200. indent += 2
  201. for child in element.children:
  202. serializeElement(child, indent)
  203. serializeElement(element, 0)
  204. return "\n".join(rv)
  205. class AttrList(object):
  206. def __init__(self, element):
  207. self.element = element
  208. self.attrs = dict(self.element.attrs)
  209. def __iter__(self):
  210. return list(self.attrs.items()).__iter__()
  211. def __setitem__(self, name, value):
  212. # If this attribute is a multi-valued attribute for this element,
  213. # turn its value into a list.
  214. list_attr = self.element.cdata_list_attributes or {}
  215. if (name in list_attr.get('*')
  216. or (self.element.name in list_attr
  217. and name in list_attr[self.element.name])):
  218. # A node that is being cloned may have already undergone
  219. # this procedure.
  220. if not isinstance(value, list):
  221. value = nonwhitespace_re.findall(value)
  222. self.element[name] = value
  223. def items(self):
  224. return list(self.attrs.items())
  225. def keys(self):
  226. return list(self.attrs.keys())
  227. def __len__(self):
  228. return len(self.attrs)
  229. def __getitem__(self, name):
  230. return self.attrs[name]
  231. def __contains__(self, name):
  232. return name in list(self.attrs.keys())
  233. class Element(treebuilder_base.Node):
  234. def __init__(self, element, soup, namespace):
  235. treebuilder_base.Node.__init__(self, element.name)
  236. self.element = element
  237. self.soup = soup
  238. self.namespace = namespace
  239. def appendChild(self, node):
  240. string_child = child = None
  241. if isinstance(node, str):
  242. # Some other piece of code decided to pass in a string
  243. # instead of creating a TextElement object to contain the
  244. # string.
  245. string_child = child = node
  246. elif isinstance(node, Tag):
  247. # Some other piece of code decided to pass in a Tag
  248. # instead of creating an Element object to contain the
  249. # Tag.
  250. child = node
  251. elif node.element.__class__ == NavigableString:
  252. string_child = child = node.element
  253. node.parent = self
  254. else:
  255. child = node.element
  256. node.parent = self
  257. if not isinstance(child, str) and child.parent is not None:
  258. node.element.extract()
  259. if (string_child is not None and self.element.contents
  260. and self.element.contents[-1].__class__ == NavigableString):
  261. # We are appending a string onto another string.
  262. # TODO This has O(n^2) performance, for input like
  263. # "a</a>a</a>a</a>..."
  264. old_element = self.element.contents[-1]
  265. new_element = self.soup.new_string(old_element + string_child)
  266. old_element.replace_with(new_element)
  267. self.soup._most_recent_element = new_element
  268. else:
  269. if isinstance(node, str):
  270. # Create a brand new NavigableString from this string.
  271. child = self.soup.new_string(node)
  272. # Tell Beautiful Soup to act as if it parsed this element
  273. # immediately after the parent's last descendant. (Or
  274. # immediately after the parent, if it has no children.)
  275. if self.element.contents:
  276. most_recent_element = self.element._last_descendant(False)
  277. elif self.element.next_element is not None:
  278. # Something from further ahead in the parse tree is
  279. # being inserted into this earlier element. This is
  280. # very annoying because it means an expensive search
  281. # for the last element in the tree.
  282. most_recent_element = self.soup._last_descendant()
  283. else:
  284. most_recent_element = self.element
  285. self.soup.object_was_parsed(
  286. child, parent=self.element,
  287. most_recent_element=most_recent_element)
  288. def getAttributes(self):
  289. if isinstance(self.element, Comment):
  290. return {}
  291. return AttrList(self.element)
  292. def setAttributes(self, attributes):
  293. if attributes is not None and len(attributes) > 0:
  294. converted_attributes = []
  295. for name, value in list(attributes.items()):
  296. if isinstance(name, tuple):
  297. new_name = NamespacedAttribute(*name)
  298. del attributes[name]
  299. attributes[new_name] = value
  300. self.soup.builder._replace_cdata_list_attribute_values(
  301. self.name, attributes)
  302. for name, value in list(attributes.items()):
  303. self.element[name] = value
  304. # The attributes may contain variables that need substitution.
  305. # Call set_up_substitutions manually.
  306. #
  307. # The Tag constructor called this method when the Tag was created,
  308. # but we just set/changed the attributes, so call it again.
  309. self.soup.builder.set_up_substitutions(self.element)
  310. attributes = property(getAttributes, setAttributes)
  311. def insertText(self, data, insertBefore=None):
  312. text = TextNode(self.soup.new_string(data), self.soup)
  313. if insertBefore:
  314. self.insertBefore(text, insertBefore)
  315. else:
  316. self.appendChild(text)
  317. def insertBefore(self, node, refNode):
  318. index = self.element.index(refNode.element)
  319. if (node.element.__class__ == NavigableString and self.element.contents
  320. and self.element.contents[index-1].__class__ == NavigableString):
  321. # (See comments in appendChild)
  322. old_node = self.element.contents[index-1]
  323. new_str = self.soup.new_string(old_node + node.element)
  324. old_node.replace_with(new_str)
  325. else:
  326. self.element.insert(index, node.element)
  327. node.parent = self
  328. def removeChild(self, node):
  329. node.element.extract()
  330. def reparentChildren(self, new_parent):
  331. """Move all of this tag's children into another tag."""
  332. # print("MOVE", self.element.contents)
  333. # print("FROM", self.element)
  334. # print("TO", new_parent.element)
  335. element = self.element
  336. new_parent_element = new_parent.element
  337. # Determine what this tag's next_element will be once all the children
  338. # are removed.
  339. final_next_element = element.next_sibling
  340. new_parents_last_descendant = new_parent_element._last_descendant(False, False)
  341. if len(new_parent_element.contents) > 0:
  342. # The new parent already contains children. We will be
  343. # appending this tag's children to the end.
  344. new_parents_last_child = new_parent_element.contents[-1]
  345. new_parents_last_descendant_next_element = new_parents_last_descendant.next_element
  346. else:
  347. # The new parent contains no children.
  348. new_parents_last_child = None
  349. new_parents_last_descendant_next_element = new_parent_element.next_element
  350. to_append = element.contents
  351. if len(to_append) > 0:
  352. # Set the first child's previous_element and previous_sibling
  353. # to elements within the new parent
  354. first_child = to_append[0]
  355. if new_parents_last_descendant is not None:
  356. first_child.previous_element = new_parents_last_descendant
  357. else:
  358. first_child.previous_element = new_parent_element
  359. first_child.previous_sibling = new_parents_last_child
  360. if new_parents_last_descendant is not None:
  361. new_parents_last_descendant.next_element = first_child
  362. else:
  363. new_parent_element.next_element = first_child
  364. if new_parents_last_child is not None:
  365. new_parents_last_child.next_sibling = first_child
  366. # Find the very last element being moved. It is now the
  367. # parent's last descendant. It has no .next_sibling and
  368. # its .next_element is whatever the previous last
  369. # descendant had.
  370. last_childs_last_descendant = to_append[-1]._last_descendant(False, True)
  371. last_childs_last_descendant.next_element = new_parents_last_descendant_next_element
  372. if new_parents_last_descendant_next_element is not None:
  373. # TODO: This code has no test coverage and I'm not sure
  374. # how to get html5lib to go through this path, but it's
  375. # just the other side of the previous line.
  376. new_parents_last_descendant_next_element.previous_element = last_childs_last_descendant
  377. last_childs_last_descendant.next_sibling = None
  378. for child in to_append:
  379. child.parent = new_parent_element
  380. new_parent_element.contents.append(child)
  381. # Now that this element has no children, change its .next_element.
  382. element.contents = []
  383. element.next_element = final_next_element
  384. # print("DONE WITH MOVE")
  385. # print("FROM", self.element)
  386. # print("TO", new_parent_element)
  387. def cloneNode(self):
  388. tag = self.soup.new_tag(self.element.name, self.namespace)
  389. node = Element(tag, self.soup, self.namespace)
  390. for key,value in self.attributes:
  391. node.attributes[key] = value
  392. return node
  393. def hasContent(self):
  394. return self.element.contents
  395. def getNameTuple(self):
  396. if self.namespace == None:
  397. return namespaces["html"], self.name
  398. else:
  399. return self.namespace, self.name
  400. nameTuple = property(getNameTuple)
  401. class TextNode(Element):
  402. def __init__(self, element, soup):
  403. treebuilder_base.Node.__init__(self, None)
  404. self.element = element
  405. self.soup = soup
  406. def cloneNode(self):
  407. raise NotImplementedError