library to compare HTML while ignoring non-functional differences
Maintained. Last release 2 months ago, commits in 3 of the last 26 weeks. Weaker on commit activity and contributor spread.
pip install htmlcomparehtmlcompare
A Python library to check whether two HTML documents are "the same". It ignores
differences which do not change what the document means, so a test does not fail
just because a template engine emitted the attributes in a different order or
wrote margin: 0px instead of margin: 0.
Usage
import htmlcompare
result = htmlcompare.compare_html(expected_html, actual_html)
if not result:
print(result)
compare_html() returns a ComparisonResult which is true when both documents
are the same. result.differences contains one Difference per mismatch,
including the path to the node which caused it.
For tests the library provides two assertions:
from htmlcompare import assert_different_html, assert_same_html
assert_same_html('<div />', '<div></div>')
assert_different_html('<br>', '<p>')
Two files can also be compared on the command line:
htmlcompare expected.html actual.html
What is ignored
- collapsible HTML whitespace which does not render with
white-space: normal: indentation around block elements, spaces at the start or end of an inline line and spaces next to<br>. Longer whitespace runs collapse to one space. <div />written as<div></div>- the order of HTML attributes, and the order of the CSS classes inside a
classattribute - an empty
styleorclassattribute, which is treated like an absent one - HTML comments
- the formatting of CSS.
styleattributes and<style>tags are parsed with a real CSS parser, so trailing semicolons, the order of declarations, the case of property, function and at-rule names, equivalent numeric spellings (.5px,0.5px), the case of dimension units (1PX,1px), the spelling of a URL (url(a.png),url("a.png")), a unit on a zero length and any whitespace CSS has no use for do not matter.
What is a difference
Something is only ignored when HTML and CSS guarantee that both spellings mean the same thing. Where the meaning can change, the documents differ:
- whitespace which CSS gives a meaning to:
.a .bis the descendant combinator and not , is not