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

使用requests模块从NSE网站下载文件报TypeError如何解决

代码修复说明

核心错误原因

requests.get()返回的resp是Response类型对象,不是你需要的二进制文件内容,写入二进制文件需要调用该对象的content属性获取字节流。

修复后的完整代码

import requests

url = r"https://www1.nseindia.com/content/historical/EQUITIES/2021/NOV/cm24NOV2021bhav.csv.zip"
# 新增浏览器UA头,规避NSE网站的反爬拦截
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
resp = requests.get(url, headers=headers, timeout=15)
# 校验请求状态,若返回4xx/5xx错误会直接抛出异常,方便定位问题
resp.raise_for_status()

with open("bhavcopy.zip", "wb") as f:
    # 核心修改:将resp替换为resp.content
    f.write(resp.content)

可选优化项

  • 若批量下载多个日期的文件,可以对日期做参数化拼接,不用手动修改url
  • 下载完成后可调用zipfile库校验压缩包完整性,避免下载到损坏文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:54:09