我有这个问题,我正在使用lxml处理一些表 - 原始源文件是mhtml格式,它们是excel文件。我需要找到包含头元素'th'元素的行。我想使用标题元素,但需要它们来自的行,以确保我按顺序处理所有内容。在lxml中测试元素时避免循环使用
所以我一直在做的是找到所有th元素,然后从那些使用e.getparent()函数获取行(因为th是一行的子元素)。但是我最终不得不拉第二个元素,一次找到它们并获取行,然后再次将它们从行中取出来解析我正在查找的数据。 这不能是这样做的最好方法,所以我想知道是否有我缺少的东西。
这里是我的代码
from lxml import html
theString=unicode(open('c:\\secexcel\\1314054-R20110331-C201-F60-SEQ132.xls').read(),'UTF-8','replace')
theTree=html.fromstring(theString)
tables=[e for e in theTree.iter() if e.tag=='table']
for table in tables :
headerCells=[e for e in table.iter() if e.tag=='th']
headerRows=[]
for headerCell in headerCells:
if headerCell.getparent().tag=='tr':
if headerCell.getparent() not in headerRows:
headerRows.append(headerCell.getparent())
for headerRow in headerRows:
newHeaderCells=[e for e in headerRow.iter() if e.tag=='th']
#Now I will extract some data and attributes from the th elements
感谢这就是我正在寻找更多pythonic比我在做什么 – PyNEwbie 2012-02-18 03:29:02