how to using python to diff two html files

二次信任 提交于 2019-12-04 03:36:25

lxml can do something similar to what you want. From the docs:

>>> from lxml.html.diff import htmldiff
>>> doc1 = '''<p>Here is some text.</p>'''
>>> doc2 = '''<p>Here is <b>a lot</b> of <i>text</i>.</p>'''
>>> print htmldiff(doc1, doc2)
<p>Here is <ins><b>a lot</b> of <i>text</i>.</ins> <del>some text.</del> </p>

I don't know of any other Python library for this specific task, but you may want to look into word-by-word diffs. They may approximate what you want.

One example is this one, implemented in both PHP and Python (save it as diff.py, then import diff)

>>> diff.htmlDiff(a,b)
>>> '<del><p>i</del> <ins><h2>i</ins> love <del>it</p></del> <ins>it </p></ins>'

i fount two python lib that's helpfull:

  1. htmltreediff
  2. htmldiff

but , both of it use python's difflib lib to diff text. but i want to use google's diff .

Checkout diff2HtmlCompare (full disclosure: I'm the author). If you're trying to just visualize the differences, then this may help you. If you are trying to extract the differences and do something with it, then you can use difflib as suggested by others (the script above just wraps difflib and uses pygments for syntax highlighting). Doug Hellmann has done a pretty good job detailing how to use difflib, I'd suggest checking out his tutorial.

Snakes and Coffee

AFAIK, python has a build in difflib that can do this.

You could use difflib.ndiff() to look for and replace the "-"/"+" with your desired HTML.

import difflib

html_1 = """
<p>i love it</p>
"""
html_2 = """
<h2>i love it </p>
"""

diff_html = ""
theDiffs = difflib.ndiff(html_1.splitlines(), html_2.splitlines())
for eachDiff in theDiffs:
    if (eachDiff[0] == "-"):
        diff_html += "<del>%s</del>" % eachDiff[1:].strip()
    elif (eachDiff[0] == "+"):
        diff_html += "<ins>%s</ins>" % eachDiff[1:].strip()

print diff_html

The result:

<del><p>i love it</p></del><ins><h2>i love it </p></ins>
monkut

Not exactly what your output is, but the standard library difflib has a simple htmldiff tool in it, which will build a html diff table for you.

import difflib

html_1 = """
<p>i love it</p>
"""
html_2 = """ 
<h2>i love it </p>
"""

htmldiff = difflib.HtmlDiff()
html_table = htmldiff.make_table([html_1], [html_2]) # each item is a list of lines
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!