html.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. """Compare two HTML documents."""
  2. from html.parser import HTMLParser
  3. from django.utils.regex_helper import _lazy_re_compile
  4. # ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020
  5. # SPACE.
  6. # https://infra.spec.whatwg.org/#ascii-whitespace
  7. ASCII_WHITESPACE = _lazy_re_compile(r'[\t\n\f\r ]+')
  8. def normalize_whitespace(string):
  9. return ASCII_WHITESPACE.sub(' ', string)
  10. class Element:
  11. def __init__(self, name, attributes):
  12. self.name = name
  13. self.attributes = sorted(attributes)
  14. self.children = []
  15. def append(self, element):
  16. if isinstance(element, str):
  17. element = normalize_whitespace(element)
  18. if self.children and isinstance(self.children[-1], str):
  19. self.children[-1] += element
  20. self.children[-1] = normalize_whitespace(self.children[-1])
  21. return
  22. elif self.children:
  23. # removing last children if it is only whitespace
  24. # this can result in incorrect dom representations since
  25. # whitespace between inline tags like <span> is significant
  26. if isinstance(self.children[-1], str) and self.children[-1].isspace():
  27. self.children.pop()
  28. if element:
  29. self.children.append(element)
  30. def finalize(self):
  31. def rstrip_last_element(children):
  32. if children and isinstance(children[-1], str):
  33. children[-1] = children[-1].rstrip()
  34. if not children[-1]:
  35. children.pop()
  36. children = rstrip_last_element(children)
  37. return children
  38. rstrip_last_element(self.children)
  39. for i, child in enumerate(self.children):
  40. if isinstance(child, str):
  41. self.children[i] = child.strip()
  42. elif hasattr(child, 'finalize'):
  43. child.finalize()
  44. def __eq__(self, element):
  45. if not hasattr(element, 'name') or self.name != element.name:
  46. return False
  47. if len(self.attributes) != len(element.attributes):
  48. return False
  49. if self.attributes != element.attributes:
  50. # attributes without a value is same as attribute with value that
  51. # equals the attributes name:
  52. # <input checked> == <input checked="checked">
  53. for i in range(len(self.attributes)):
  54. attr, value = self.attributes[i]
  55. other_attr, other_value = element.attributes[i]
  56. if value is None:
  57. value = attr
  58. if other_value is None:
  59. other_value = other_attr
  60. if attr != other_attr or value != other_value:
  61. return False
  62. return self.children == element.children
  63. def __hash__(self):
  64. return hash((self.name, *self.attributes))
  65. def _count(self, element, count=True):
  66. if not isinstance(element, str) and self == element:
  67. return 1
  68. if isinstance(element, RootElement) and self.children == element.children:
  69. return 1
  70. i = 0
  71. elem_child_idx = 0
  72. for child in self.children:
  73. # child is text content and element is also text content, then
  74. # make a simple "text" in "text"
  75. if isinstance(child, str):
  76. if isinstance(element, str):
  77. if count:
  78. i += child.count(element)
  79. elif element in child:
  80. return 1
  81. else:
  82. # Look for element wholly within this child.
  83. i += child._count(element, count=count)
  84. if not count and i:
  85. return i
  86. # Also look for a sequence of element's children among self's
  87. # children. self.children == element.children is tested above,
  88. # but will fail if self has additional children. Ex: '<a/><b/>'
  89. # is contained in '<a/><b/><c/>'.
  90. if isinstance(element, RootElement) and element.children:
  91. elem_child = element.children[elem_child_idx]
  92. # Start or continue match, advance index.
  93. if elem_child == child:
  94. elem_child_idx += 1
  95. # Match found, reset index.
  96. if elem_child_idx == len(element.children):
  97. i += 1
  98. elem_child_idx = 0
  99. # No match, reset index.
  100. else:
  101. elem_child_idx = 0
  102. return i
  103. def __contains__(self, element):
  104. return self._count(element, count=False) > 0
  105. def count(self, element):
  106. return self._count(element, count=True)
  107. def __getitem__(self, key):
  108. return self.children[key]
  109. def __str__(self):
  110. output = '<%s' % self.name
  111. for key, value in self.attributes:
  112. if value:
  113. output += ' %s="%s"' % (key, value)
  114. else:
  115. output += ' %s' % key
  116. if self.children:
  117. output += '>\n'
  118. output += ''.join(str(c) for c in self.children)
  119. output += '\n</%s>' % self.name
  120. else:
  121. output += '>'
  122. return output
  123. def __repr__(self):
  124. return str(self)
  125. class RootElement(Element):
  126. def __init__(self):
  127. super().__init__(None, ())
  128. def __str__(self):
  129. return ''.join(str(c) for c in self.children)
  130. class HTMLParseError(Exception):
  131. pass
  132. class Parser(HTMLParser):
  133. # https://html.spec.whatwg.org/#void-elements
  134. SELF_CLOSING_TAGS = {
  135. 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta',
  136. 'param', 'source', 'track', 'wbr',
  137. # Deprecated tags
  138. 'frame', 'spacer',
  139. }
  140. def __init__(self):
  141. super().__init__()
  142. self.root = RootElement()
  143. self.open_tags = []
  144. self.element_positions = {}
  145. def error(self, msg):
  146. raise HTMLParseError(msg, self.getpos())
  147. def format_position(self, position=None, element=None):
  148. if not position and element:
  149. position = self.element_positions[element]
  150. if position is None:
  151. position = self.getpos()
  152. if hasattr(position, 'lineno'):
  153. position = position.lineno, position.offset
  154. return 'Line %d, Column %d' % position
  155. @property
  156. def current(self):
  157. if self.open_tags:
  158. return self.open_tags[-1]
  159. else:
  160. return self.root
  161. def handle_startendtag(self, tag, attrs):
  162. self.handle_starttag(tag, attrs)
  163. if tag not in self.SELF_CLOSING_TAGS:
  164. self.handle_endtag(tag)
  165. def handle_starttag(self, tag, attrs):
  166. # Special case handling of 'class' attribute, so that comparisons of DOM
  167. # instances are not sensitive to ordering of classes.
  168. attrs = [
  169. (name, ' '.join(sorted(value for value in ASCII_WHITESPACE.split(value) if value)))
  170. if name == "class"
  171. else (name, value)
  172. for name, value in attrs
  173. ]
  174. element = Element(tag, attrs)
  175. self.current.append(element)
  176. if tag not in self.SELF_CLOSING_TAGS:
  177. self.open_tags.append(element)
  178. self.element_positions[element] = self.getpos()
  179. def handle_endtag(self, tag):
  180. if not self.open_tags:
  181. self.error("Unexpected end tag `%s` (%s)" % (
  182. tag, self.format_position()))
  183. element = self.open_tags.pop()
  184. while element.name != tag:
  185. if not self.open_tags:
  186. self.error("Unexpected end tag `%s` (%s)" % (
  187. tag, self.format_position()))
  188. element = self.open_tags.pop()
  189. def handle_data(self, data):
  190. self.current.append(data)
  191. def parse_html(html):
  192. """
  193. Take a string that contains HTML and turn it into a Python object structure
  194. that can be easily compared against other HTML on semantic equivalence.
  195. Syntactical differences like which quotation is used on arguments will be
  196. ignored.
  197. """
  198. parser = Parser()
  199. parser.feed(html)
  200. parser.close()
  201. document = parser.root
  202. document.finalize()
  203. # Removing ROOT element if it's not necessary
  204. if len(document.children) == 1 and not isinstance(document.children[0], str):
  205. document = document.children[0]
  206. return document