首页 > 解决方案 > 从 read_html 源写入 csv 文件

问题描述

我无法将 html 表(表 2)导出到 csv 文件。我尝试在对象 pd.read_html 上使用 to_csv 但不工作

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import html.parser
import pandas as pd
import time

driver=webdriver.Chrome("C:/Users/Juan Diego Bernate V/Documents/Python/Practica/APIs/chromedriver.exe")

driver.get('https://www.ambito.com/contenidos/dolar-futuro.html')
res=driver.execute_script("return document.documentElement.outerHTML")
html=driver.page_source
soup= BeautifulSoup(html, 'lxml')
tabla=soup.find_all('table')
tabla2=pd.read_html(html)

dia = time.strftime("%Y%m%d")
ruta='C:/Users/Juan Diego Bernate V/'
nombre= ruta+ 'dolar_fut_rofex_2'+dia+'.csv'

tabla2.to_csv(nombre)
print (tabla2)
print (tabla)

这是错误信息,我写了我使用的所有代码,之前,我认为它不相关。

DevTools 监听 ws://127.0.0.1:54234/devtools/browser/6a47dd26-ab5d-4318-b858-226180882e0f Traceback(最近一次调用最后):文件“WSDinamicoRofex.py”,第 34 行,在 tabla2.to_csv(nombre ) AttributeError: 'list' object has no attribute 'to_csv' 希望你能帮助我

标签: pythonbeautifulsoup

解决方案


我无法完全运行您的示例,但请尝试astropy. 这样的事情应该做:

from astropy.io import ascii

# your code here

tbl = ascii.read(html_table, format='html')

这会产生一个astropy Table,它很容易操作,然后您可以使用保存到另一个文件

ascii.write(tbl, 'table.csv', format='csv')

或者,等效地,

tbl.write('table.csv', format='ascii.csv')

推荐阅读