将 HTML 与 difflib 进行比较

Comparing HTML with difflib

我希望获得 this 页面的 内容 的可靠差异(结构变化很少见,因此可以忽略)。更具体地说,我需要进行的唯一更改是添加了一个新的指令 ID:

为了感受一下difflib会产生什么,我先比较两个相同 HTML的内容,希望得到没有回复:

url = 'https://secure.ssa.gov/apps10/reference.nsf/instructiontypecode!openview&restricttocategory=POMT'
response = urllib.urlopen(url
content = response.read()
import difflib
d = difflib.Differ()

diffed = d.compare(content, content)

由于 difflib 模仿 UNIX diff 实用程序,我希望 diffed 不包含任何内容(或给出一些序列相同的指示,但但是,如果我 '\n'.join diffed,我会得到 something resembling HTML,(尽管它不会在浏览器中呈现)

确实,如果我采用区分两个字符的最简单的情况:

diffed = d.compare('a', 'a')

diffed.next() 生成以下内容:

'  a'

所以我要么期望 difflib 不能或不会提供某些东西(我应该改变策略),要么我在滥用它? HTML?

有哪些可行的替代方案

Differ.compare() 的参数应该是字符串序列。如果您使用两个字符串,它们将分别被视为序列,因此逐个字符进行比较。

所以你的例子应该重写为:

url = 'https://secure.ssa.gov/apps10/reference.nsf/instructiontypecode!openview&restricttocategory=POMT'
response = urllib.urlopen(url)
content = response.readlines()  # get response as list of lines
import difflib
d = difflib.Differ()

diffed = d.compare(content, content)
print('\n'.join(diffed))

如果您只想比较 html 文件的内容,您应该使用解析器来处理它并只获取没有标签的文本,例如通过使用 BeautifulSoup 的 soup.stripped_strings:

soup = bs4.BeautifulSoup(html_content)
diff = d.compare(list(soup.stripped_strings), list_to_compare_to)
print('\n'.join(diff))