在Python中将html转换为excel

我试图将以下站点中的表转换为xls表:

http://www.dekel.co.il/madad-lazarchan

以下是我从研究中得出的代码:

from bs4 import BeautifulSoup import pandas as pd from urllib2 import urlopen import requests import csv url='http://www.dekel.co.il/madad-lazarchan' table = pd.read_html(requests.get(url).text, attrs={"class" : "medadimborder"}) print table</code> 

我怎样才能得到它正确显示标题,并输出到CSV或XLS文件?

如果我添加以下内容:

 table.to_csv('test.csv') 

而不是打印行我得到这个错误:

 'list' object has no attribute 'to_csv' 

提前致谢!

好的根据意见,也许我不应该使用pandas或read_html,因为我想要一个表,而不是一个列表。 我写了下面的代码,但现在打印输出有分隔符,看起来像我失去了标题行。 还不知道如何将其导出到CSV文件。

from bs4 import BeautifulSoup import urllib2 import csv soup = BeautifulSoup(urllib2.urlopen('http://www.dekel.co.il/madad-lazarchan').read(), 'html') data = [] table = soup.find("table", attrs={"class" : "medadimborder"}) table_body = table.find('tbody') rows = table_body.findAll('tr') for row in rows: cols = row.findAll('td') cols = [ele.text.strip() for ele in cols] print cols

[u'01 / 16',u'130.7915',u'122.4640',u'117.9807',u'112.2557',u'105.8017',u'100.5720',u'98.6'] [u'12 / 15' ,u'131.4547',u'123.0850',u'118.5790',u'112.8249',u'106.3383',u'101.0820',u'99.1'] [u'11 / 15',u'131.5874',u '123.2092',u'118.6986',u'112.9387',u'106.4456',u'101.1840',u'99.2']

您可以使用可用的Python包来处理Excel文件。 这里是一个列表 。

你的“表”variables不是一个pandas数据框,而是一个二维列表,其第一个也是唯一的元素是pandas数据框。 从逻辑上讲,在python列表中调用pandas方法将不起作用,并引发AttributeError 。 Python的内置type()dir()揭示了这一点:

 >>> type(table) <class 'list'> >>> type(table[0]) <class 'pandas.core.frame.DataFrame'> # no error >>> table[0].to_csv('test.csv') >>> # 2D to 1D list >>> table = table[0] >>> table.to_csv('test.csv') >>>