Python请求获取返回nse印度网站的响应代码401 [英] Python Requests get returns response code 401 for nse india website

查看:21
本文介绍了Python请求获取返回nse印度网站的响应代码401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个程序从https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY获取json数据但是从今天早上起它就无法工作,因为它返回 .不过,该链接在 chrome 上加载良好.有没有办法在不使用硒的情况下解决这个问题?

I use this program to get the json data from https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY but since this morning it's not working as it returns <Response [401]>. The link loads fine on chrome though. Is there any way to fix this without using selenium ?

import json
import requests

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'}

res = requests.get("https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY", headers=headers)
print(res)

推荐答案

试试这个:

import requests

baseurl = "https://www.nseindia.com/"
url = f"https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
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'}
session = requests.Session()
request = session.get(baseurl, headers=headers, timeout=5)
cookies = dict(request.cookies)
response = session.get(url, headers=headers, timeout=5, cookies=cookies)
print(response.json())

要多次访问 NSE(api 的)站点,然后在每个后续请求中设置 cookies:

To access the NSE (api's) site multiple times then set cookies in each subsequent requests:

response = session.get(url, headers=headers, timeout=5, cookies=cookies)

这篇关于Python请求获取返回nse印度网站的响应代码401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆