繁体   English   中英

在 Python 中将 html 转换为 excel

[英]Converting html to excel in Python

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

提前致谢!

好的,根据评论,也许我不应该使用 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'/12'] , u'131.4547', u'123.0850', u'118.5790', u'112.8249', u'106.3383', u'101.0820', u'99.1'] [u',5'173'] '123.2092'、u'118.6986'、u'112.9387'、u'106.4456'、u'101.1840'、u'99.2']

您可以使用可用于处理 Excel 文件的 python 包。 这是一个列表

pandas.read_html 返回数据帧列表而不是单个数据帧。 您必须在返回的列表中指定 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') 

问候

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM