2017-05-24 205 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