You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas.read_csv()加载URL触发404错误,求排查解决方法

解决pandas.read_csv加载Yahoo Finance URL返回404的问题

问题原因

你构造的URL是Yahoo Finance的网页展示地址,并非提供CSV数据的接口地址。pandas.read_csv()需要直接指向可下载的CSV文件链接,而该网页地址返回的是HTML内容,服务器不会将其识别为CSV资源,因此触发404错误。

解决方案

方法1:使用yfinance库(推荐)

Yahoo Finance官方推荐通过yfinance库获取金融数据,它封装了正确的接口,无需手动构造URL,稳定性更高:

import yfinance as yf

stockcode = 'SBIN.NS'
# 时间范围支持UNIX时间戳或datetime对象
start = 1661711400
end = 1662143399

# 获取周度历史数据
stockHistoricalPrice = yf.download(stockcode, start=start, end=end, interval='1wk')
print(stockHistoricalPrice.head())

先执行安装命令:pip install yfinance

方法2:构造正确的CSV下载接口(不推荐,接口易变更)

如果一定要用read_csv,需要使用Yahoo的CSV数据接口,同时要添加请求头模拟浏览器访问以绕过反爬限制:

import pandas as pd
import requests

st = str(1661711400)
et = str(1662143399)
stockcode = 'SBIN'

# 构造CSV数据接口链接
url = f'https://query1.finance.yahoo.com/v7/finance/download/{stockcode}.NS?period1={st}&period2={et}&interval=1wk&events=history&includeAdjustedClose=true'

# 添加浏览器请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

# 获取并读取CSV数据
response = requests.get(url, headers=headers)
stockHistoricalPrice = pd.read_csv(pd.compat.StringIO(response.text))
print(stockHistoricalPrice.head())

注意:该接口可能随Yahoo的策略调整随时失效,不建议长期依赖。

内容的提问来源于stack exchange,提问作者skye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:55:18