我目前正在尝试解决一个编程问题。我正在尝试在任何HTML页面中找到重复的结构,并且正在尝试检索这些元素的值。
例如,我有一个带有重复元素的HTML页面,如以下内容:
<html>
<body>
<ul>
<li>green</li>
<li>orange</li>
<li>red</li>
</ul>
</body>
在此代码中,我想检测到有一个重复块(" li"项目),我想提取它们的值。另一个HTML示例:
<table>
<tr>
<td>1</td>
<td>John</td>
</tr>
<tr>
<td>2</td>
<td>Simon</td>
</tr>
</table>
在此示例中,我想检测到结构是重复的,并从中获取值[1,John]和[2,Simon]。
我的问题是:是否有一个简单的算法可以做类似的事情,或者,如果没有,您将如何处理这样的事情?
一个相当基本的python程序,该程序检测重复的TR-TD-TD标签序列和重复的TD标签,如下所示。使用您的第二个HTML示例保存在文件xml.html
中,程序打印出来:
tr.td.td
td 1
td John
tr.td.td
td 2
td Simon
Counter({'td': 4, 'tr.td.td': 2, 'table.tr.tr': 1})
#!/usr/bin/env python
from xml.etree import cElementTree as ET
from collections import Counter
def sot(r, depth):
tags = r.tag
for e in r.getchildren():
tags += '.' + sot(e, depth+1)
r.tail = tags
cc[r.tail] += 1
return r.tag
def tot(r, depth):
if cc[r.tail] > 1:
print r.tail, r.text
for e in r.getchildren():
tot(e, depth+1)
cc = Counter()
p=ET.parse ("xml.html")
sot(p.getroot(), 0)
tot(p.getroot(), 0)
print cc