简体   繁体   中英

how to using python to diff two html files

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 ?

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 .

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>

AFAIK,python有一个difflib构建,可以做到这一点。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM