使用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
相关产品推荐
相关产品推荐

