我有這個問題,我正在使用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