2012-02-16 57 views
0

我有这个问题,我正在使用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 

回答

1

迭代所有tr标签,并继续前进到下一个,当你发现没有th内。

编辑。这就是:

from lxml import html 
theString=unicode(open('c:\\secexcel\\1314054-R20110331-C201-F60-SEQ132.xls').read(),'UTF-8','replace') 
theTree=html.fromstring(theString) 
for table in theTree.iter('table'): 
    for row in table.findall('tr'): 
     headerCells = list(row.findall('th')) 
     if headerCells: 
      #extract data from row and headerCells 
+0

感谢这就是我正在寻找更多pythonic比我在做什么 – PyNEwbie 2012-02-18 03:29:02

1

避免做两次,你可以使用由行元素键一本字典和积累的所有标题单元从给定的行成assocated列表,可以在单次通过完成表格的元素。为了保持行的排列顺序,可以使用内置collections模块中的OrderedDict。这将允许沿着这些线写东西:

from lxml import html 
from collections import OrderedDict 
f='c:\\secexcel\\1314054-R20110331-C201-F60-SEQ132.xls' 
theString=unicode(open(f).read(),'UTF-8','replace') 
theTree=html.fromstring(theString) 
tables=[e for e in theTree.iter() if e.tag=='table'] 
for table in tables: 
    headerRowDict=OrderedDict() 
    for e in table.iter(): 
     if e.tag=='th': 
      headerRowDict.setdefault(e.getparent(), []).append(e) 
    for headerRow in headerRowDict: 
     for headerRowCell in headerRow: 
      # extract data and attributes from the <th> element from the row...