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

从NSEIndia获取股票期权数据时遇JSONDecodeError问题求助

解决NSEIndia股票期权API的JSONDecodeError问题

问题原因

NSEIndia的股票期权API(option-chain-equities)比指数期权API有更严格的会话验证要求,第一次请求返回的Cookie不足以通过校验,导致服务器返回非JSON内容(比如403拦截页面),直接调用.json()就会触发JSONDecodeError。

解决方案

1. 先获取完整会话Cookie

在请求期权API前,先访问NSE主页,获取服务器要求的全量会话Cookie,确保后续API请求能通过验证。

2. 增加响应校验逻辑

解析JSON前先检查响应状态码,同时捕获解析异常,方便排查返回内容的问题。

3. 利用会话自动管理Cookie

借助requests.Session()的特性,无需手动提取和传递Cookie,会话会自动维护Cookie状态。

修改后的代码

import requests
import json
import pandas as pd

expiry_dt = '27-Oct-2022'
url = 'https://www.nseindia.com/api/option-chain-equities?symbol=ICICIBANK'
headers = {
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36',
    'accept-language': 'en,gu;q=0.9,hi;q=0.8',
    'accept-encoding': 'gzip, deflate, br'
}

session = requests.Session()

try:
    # 先访问NSE主页初始化会话Cookie
    session.get('https://www.nseindia.com', headers=headers)
    # 请求股票期权API
    response = session.get(url, headers=headers)
    # 检查请求是否成功
    response.raise_for_status()
    
    # 解析JSON数据
    json_data = response.json()
    print("数据获取成功")
    
    # 示例:提取指定到期日的期权数据并转为DataFrame
    if 'records' in json_data:
        target_data = [item for item in json_data['records']['data'] if item['expiryDate'] == expiry_dt]
        df = pd.DataFrame(target_data)
        print(df.head())
        
except requests.exceptions.HTTPError as e:
    print(f"请求错误: {e}")
    print("响应内容预览:", response.text[:500])
except json.JSONDecodeError as e:
    print(f"JSON解析错误: {e}")
    print("响应内容预览:", response.text[:500])

额外提示

  • 若后续再次出现验证问题,可以更新user-agent为当前浏览器的最新版本字符串。
  • 避免高频请求API,防止被NSEIndia限制访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:55:23