【问题标题】:unable to fetch json data - JSONDecodeError: Expecting value无法获取 json 数据 - JSONDecodeError:期望值
【发布时间】:2021-05-17 12:59:13
【问题描述】:

我是 python 新手,正在为以下问题苦苦挣扎。

网站页面的 URL 是https://www.nseindia.com/market-data/equity-derivatives-watch,当我们选择“Nifty 50 Futures”时,经过检查,我们得到的 api URL 是 https://www.nseindia.com/api/liveEquity-derivatives?index=nse50_fut。 现在的问题是这个 json 在浏览器上打开,但是从 python 中它没有打开并给出 JSONDecodeError 错误。我已经包含了正确的标题,但仍然失败。

另一个观察结果是,当我直接在浏览器中加载此 api 时,python 代码会获取一次 json 数据,但之后就无法正常工作了。我注意到的一件事是每次页面刷新都会设置一个新的 cookie。

任何人都可以在我失踪的地方帮助我。

代码:

    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
              "accept-language": "en-US,en;q=0.9", "accept-encoding": "gzip, deflate, br", "accept": "*/*"}

    URL = "https://www.nseindia.com/api/liveEquity-derivatives?index=nse50_fut"
    fut_json = requests.get(URL, headers = header).json()
    print(fut_json)


  File "C:\ProgramData\Anaconda3\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())

JSONDecodeError: Expecting value

【问题讨论】:

  • 不要使用.json() 解析目录,检查.status_code。如果是 200 则只解析。在这种情况下,尝试您的代码会给出401,这意味着未经授权。所以你需要自己授权,然后才会得到json

标签: python json python-requests


【解决方案1】:

你需要cookies 才能得到JSON 的响应,因为没有它们你会得到Resource not found。

方法如下:

import requests

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
}

with requests.Session() as s:
    r = s.get("https://www.nseindia.com", headers=headers)
    api_url = "https://www.nseindia.com/api/liveEquity-derivatives?index=nse50_fut"
    response = s.get(api_url, headers=headers).json()
    print(response["marketStatus"]["marketStatusMessage"])

输出:

Market is Closed

【讨论】:

    猜你喜欢
    • 2021-05-28
    • 2020-09-04
    • 2021-02-23
    • 2017-12-28
    • 2021-03-05
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多