2017-05-24 203 views
0

我正在使用以下代碼寫入Excel文件。請糾正我。 我在這種情況下解析一個HTML頁面。我的目標是找到表格元素並將其寫入列。Python:AttributeError:'str'對象沒有屬性'font'

for row in table.findAll('tr', { "class" : "product-row" }): 
col = row.findAll('td') 

i=1 
Image = col[0].a.img['src'] 
Name = col[1].a.text 
Width = col[3].text 

record = (Image,Name,Width) 

book = xlwt.Workbook(encoding="utf-8") 
sheet1 = book.add_sheet("Sheet 1") 

sheet1.write(i, Image, Name, Width) 

book.save("trial.xls") 

它顯示了以下錯誤:

--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-179-1d146cb8794d> in <module>() 
    14  sheet1 = book.add_sheet("Sheet 1") 
    15 
---> 16  sheet1.write(i, Image, Name, Width) 
    17 
    18  book.save("trial.xls") 

C:\Users\Santosh\Anaconda3\lib\site-packages\xlwt\Worksheet.py in 
write(self, r, c, label, style) 
    1086   :class:`~xlwt.Style.XFStyle` object. 
    1087   """ 
-> 1088   self.row(r).write(c, label, style) 
    1089 
    1090  def write_rich_text(self, r, c, rich_text_list, 
style=Style.default_style): 

C:\Users\Santosh\Anaconda3\lib\site-packages\xlwt\Row.py in write(self, col, 
label, style) 
    233 
    234  def write(self, col, label, style=Style.default_style): 
--> 235   self.__adjust_height(style) 
    236   self.__adjust_bound_col_idx(col) 
    237   style_index = self.__parent_wb.add_style(style) 

C:\Users\Santosh\Anaconda3\lib\site-packages\xlwt\Row.py in 
__adjust_height(self, style) 
    63 
    64  def __adjust_height(self, style): 
---> 65   twips = style.font.height 
    66   points = float(twips)/20.0 
    67   # Cell height in pixels can be calcuted by following approx. 
formula: 

AttributeError: 'str' object has no attribute 'font 

回答

0

您沒有使用正確的方法.write()。提供行和列索引,然後是要寫入單元格的數據:

record = (Image, Name, Width) 

for col_index, item in enumerate(record): 
    sheet1.write(i, col_index, item) 
+0

我是python的新手。你能否讓我更多地瞭解行列索引。或任何我可以參考的例子。 – Santosh

+0

@Santosh當然,我已經鏈接瞭解釋如何使用方法和參數含義的方法文檔。 – alecxe

+0

謝謝。有效!但是需要編寫一整套記錄。所以我想我需要把它們放在一個循環中。 – Santosh