You need to enable JavaScript to run this app. 使用Python requests库下载zip压缩csv文件返回404如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用Python requests库下载zip压缩csv文件返回404如何解决

NSE历史衍生品Bhavcopy文件编程下载方案

NSE站点对历史数据下载接口做了两层访问校验,直接请求下载直链会被拦截返回404:

  • 必须携带从归档页面获取的有效会话Cookie
  • 请求头必须配置正确的Referer参数,值为归档页面地址

实现代码(Python + requests)

import requests

# 配置全局请求头
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",
    "Referer": "https://www1.nseindia.com/products/content/derivatives/equities/archieve_fo.htm"
}

# 创建会话自动保持Cookie
session = requests.Session()
session.headers.update(headers)

# 第一步:先访问归档页面获取有效Cookie
archive_resp = session.get("https://www1.nseindia.com/products/content/derivatives/equities/archieve_fo.htm", timeout=10)
if archive_resp.status_code != 200:
    raise Exception("访问归档页面失败,无法获取有效会话")

# 第二步:请求下载直链
download_url = "https://www1.nseindia.com/content/historical/DERIVATIVES/2021/JUN/fo18JUN2021bhav.csv.zip"
download_resp = session.get(download_url, timeout=15)

# 保存文件
if download_resp.status_code == 200:
    with open("fo18JUN2021bhav.csv.zip", "wb") as f:
        f.write(download_resp.content)
    print("文件下载完成")
else:
    print(f"下载失败,状态码:{download_resp.status_code}")

注意事项

  • 不要短时间内发起大量请求,NSE会触发IP限流,短时间内无法访问站点
  • 构造下载链接时注意月份为大写3位英文字母、日期和年份格式要和对应路径匹配
  • 如果请求失败可以更换User-Agent参数,或者间隔几分钟后重试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 13:15:06