【问题标题】:Converting html to excel in Python在 Python 中将 html 转换为 excel
【发布时间】:2016-06-20 06:22:17
【问题描述】:

我正在尝试将以下站点中的表格转换为 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'

提前致谢!

好吧,根据 cmets,也许我不应该使用 panda 或 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 html excel csv


    【解决方案1】:

    您可以使用可用于处理 Excel 文件的 python 包。这是list

    【讨论】:

    【解决方案2】:

    pandas.read_html 返回一个 DataFrame 列表,而不是一个。您必须在返回的列表中指定 DataFrame 的索引(在这种情况下索引 = 0):

    https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv

    #now the result of read_html will be named 'tables', which is a list of DataFrames
    tables = pd.read_html(requests.get(url).text, attrs={"class" : "medadimborder"})
    #assigning the first element of the list of DataFrames 'tables' into DataFrame 'table'
    table = tables[0]
    #converting into csv
    table.to_csv('test.csv') 
    

    问候

    【讨论】:

      【解决方案3】:

      您的“表”变量不是熊猫数据框,而是一个二维列表,其第一个也是唯一的元素是熊猫数据框。从逻辑上讲,在 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')
      >>> 
      

      【讨论】:

      • 更新了初始问题以显示没有熊猫的新代码,因为我想要一个表格而不是列表。
      猜你喜欢
      • 2021-12-25
      • 2017-05-06
      • 2012-03-22
      • 1970-01-01
      • 2014-11-19
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      相关资源
      最近更新 更多