how to using python to diff two html files

早过忘川 提交于 2019-12-09 16:24:29

问题


i want use python to diff two html files:

example :

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

the diff file will like this :

diff_html = """
<del><p>i love it</p></dev><ins><h2>i love it</h2></ins>
"""

is there such python lib help me do this ?


回答1:


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>'



回答2:


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 .




回答3:


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.




回答4:


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




回答5:


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>



回答6:


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


来源:https://stackoverflow.com/questions/9562269/how-to-using-python-to-diff-two-html-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!