3 回答

TA贡献1780条经验 获得超5个赞
如何使用这个:
解析HTML表到Python列表?
但是,请使用collections.OrderedDict()而不是简单的字典来保留顺序。有了字典后,从字典中获取文本并设置其格式非常非常容易:
使用@Colt 45的解决方案:
import xml.etree.ElementTree
import collections
s = """\
<table>
<tr>
<th>Height</th>
<th>Width</th>
<th>Depth</th>
</tr>
<tr>
<td>10</td>
<td>12</td>
<td>5</td>
</tr>
<tr>
<td>0</td>
<td>3</td>
<td>678</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>4</td>
</tr>
</table>
"""
table = xml.etree.ElementTree.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
values = [col.text for col in row]
for key, value in collections.OrderedDict(zip(headers, values)).iteritems():
print key, value
输出:
Height 10
Width 12
Depth 5
Height 0
Width 3
Depth 678
Height 5
Width 3
Depth 4
添加回答
举报