2012-02-16 54 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...