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

使用Python爬取NSE网站股票期货数据报JSONDecodeError如何解决

报错原因
  • 核心原因是请求返回内容并非JSON格式,调用.json()方法解析失败。你当前请求的https://www.nseindia.com/get-quotes/derivatives?symbol=WIPRO是前端页面地址,返回内容为HTML文档,无法直接解析为JSON。
  • 代码中User-Agent存在拼接错误,like Gecko和Chrome/80.0.3987.149前缺少空格,导致UA格式非法,被NSE网站反爬机制直接拦截,返回异常内容。
  • 缺少必要的referer请求头,NSE接口会校验请求来源,未携带合法referer的请求会被拒绝返回有效数据。
解决方法
  1. 将请求地址替换为NSE官方衍生品数据API接口:https://www.nseindia.com/api/quote-derivative?symbol=WIPRO,该接口才会返回JSON格式的数据。
  2. 修正User-Agent的拼接错误,保证UA格式合规。
  3. 在请求头中添加referer字段,值设置为对应的前端页面地址。
  4. 新增状态码和内容格式校验逻辑,避免直接调用.json()触发报错。

修正后代码示例

import requests

url_oc = "https://www.nseindia.com/get-quotes"
# 替换为真实数据API地址
api_url = "https://www.nseindia.com/api/quote-derivative?symbol=WIPRO"
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
    'accept-language': 'en,gu;q=0.9,hi;q=0.8',
    'accept-encoding': 'gzip, deflate, br',
    # 新增referer请求头
    'referer': 'https://www.nseindia.com/get-quotes/derivatives?symbol=WIPRO'
}

session = requests.Session()
# 先请求页面获取有效cookie
base_resp = session.get(url_oc, headers=headers, timeout=10)
cookies = dict(base_resp.cookies)

# 请求数据接口
data_resp = session.get(api_url, headers=headers, timeout=10, cookies=cookies)

if data_resp.status_code == 200:
    try:
        stock_data = data_resp.json()
        print(stock_data)
    except:
        # 打印前500个字符排查返回内容问题
        print("返回内容非JSON格式,前500字符:", data_resp.text[:500])
else:
    print(f"请求失败,状态码:{data_resp.status_code}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:18:00