You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

237 lines
7.7 KiB

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