需要解决从网站下载xlsx的问题

2024-09-28 22:01:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过python从url链接下载xslx电子表格中提供的数据。我的第一种方法是将其读入数据帧,并将其保存到一个可以通过另一个脚本操作的文件中

我已经意识到,由于安全问题,xlrd不再支持xlsx。我目前的解决方法是下载到一个单独的文件,转换成xls和VT,然后再进行初始处理/操作。我是python新手,不知道这是否是实现此目标的最佳方法。我认为这种方法存在潜在问题,因为安全问题仍然存在。这个特定的文档可能每天都被许多机构下载,所以黑客攻击源文档和部署bug的动机很高。我是不是想得太多了

您将使用什么方法从静态url将xlsx调用到pandas中…此外,这是我的下一个问题-从动态url下载文档以及有关在何处查找的任何提示都会很有帮助

下面是我的原始源代码,我要解决的问题是维护一个包含所有s&;p500成分及其当前权重

多谢各位

# packages
import pandas as pd

url = 'https://www.ssga.com/us/en/institutional/etfs/library-content/products/fund-data/etfs/us/holdings-daily-us-en-spy.xlsx'

# Load the first sheet of the Excel file into a data frame
df = pd.read_excel(url, sheet_name=0, header=1)

# View the first ten rows
df.head(10)

#is it worth it to download file to a repisotory, convert to xls, then read in?

Tags: 文件theto数据方法文档urlpandas
1条回答
网友
1楼 · 发布于 2024-09-28 22:01:02

您始终可以通过请求发出请求,然后将xlsx读入数据帧,如下所示:

import pandas as pd
import requests

from io import BytesIO

url = ("https://www.ssga.com/us/en/institutional/etfs/library-content/"
       "products/fund-data/etfs/us/holdings-daily-us-en-spy.xlsx")

r = requests.get(url)
bts = BytesIO(r.content)
df = pd.read_excel(bts)

我不确定是否存在安全问题,但这相当于在浏览器中发出相同的请求。至于动态url,如果您能够确定url的哪些部分正在更改,您可以按如下方式对其进行修改

stock = 'spy'
url = ("https://www.ssga.com/us/en/institutional/etfs/library-content/"
       f"products/fund-data/etfs/us/holdings-daily-us-en-{stock}.xlsx")

相关问题 更多 >