I am trying to get json data in a container using following code:
import requests
import pandas as pd
import json
from bs4 import BeautifulSoup
url = 'https://www.nseindia.com/api/quote-derivative?symbol=NIFTY&identifier=FUTIDXNIFTY29-02-2024XX0.00'
headers = {
'accept':'*/*',
'accept-encoding':'gzip, deflate, br',
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
session = requests.Session()
data = session.get(url, headers = headers).json()
It throws me following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
TL;DR --> Add cookies to the request
The website just checks if the request you have sent has the right cookies. So a good approach to get the information is to copy your cookies and adding it into your request. Here's a PoC (I didn't use
requests.session, and I've redacted the actual values of cookies, but you should be able to implement this approach in your code):Now of course the cookies won't be
redacted, I hid it because of privacy reasons. If you do similar approach your code will work out.