简体   繁体   English

Python 请求获取 nse 印度网站返回响应代码 401

[英]Python Requests get returns response code 401 for nse india website

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]> .我使用此程序从https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY获取 json 数据,但从今天早上开始它无法正常工作,因为它返回<Response [401]> The link loads fine on chrome though.尽管该链接在 chrome 上加载正常。 Is there any way to fix this without using selenium?有什么办法可以不使用 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)

Try this:尝试这个:

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())

To access the NSE (api's) site multiple times then set cookies in each subsequent requests:要多次访问 NSE(api)站点,然后在每个后续请求中设置cookies

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

对于执行和操作,您首先必须执行登录请求调用,该调用将返回会话 ID。此会话 ID 将用于下一个请求的标头部分,以进行身份​​验证并返回有效响应

Even I'm getting the same error from today morning.即使我从今天早上开始也遇到同样的错误。 Earlier I used to face this issue only on servers hosted outside India.早些时候,我曾经只在印度境外托管的服务器上遇到过这个问题。 But now looks like they are trying to stop scraping altogether.但现在看起来他们正试图完全停止刮擦。

Really interested in finding a solution to this.真的有兴趣找到解决方案。

Also for the time being the old website still seems to be working.目前, 旧网站似乎仍在运行。 I know it's not a permanent solution but I'm using that as a stop gap until I find a more permanent solution.我知道这不是一个永久的解决方案,但我将其用作止损,直到找到更永久的解决方案。

Got the same error with Java. Solution is得到与 Java 相同的错误。解决方案是

  • first make connection to https://nseindia.com .首先连接到https://nseindia.com
  • And then read the cookie returned by the server.然后读取服务器返回的cookie。
  • Add the same cookie in your request.在您的请求中添加相同的 cookie。

Depending on which implementation you are using to make ssl calls, you will have to find appropriate methods to get and set cookies. Dont know why NSE site has to look for a cookie when the data is publicly enabled.根据您使用哪种实现来进行 ssl 调用,您将必须找到适当的方法来获取和设置 cookies。不知道为什么 NSE 站点在公开启用数据时必须查找 cookie。 Some extra technology applied by nse for sure.. nse 肯定会应用一些额外的技术..

I tried same thing with node js please use node js ide link here for online ide please review my code我用 node js 尝试了同样的事情,请在此处使用 node js ide链接进行在线 ide请查看我的代码

const axios = require('axios');


let cookie;
let url_oc = "https://www.nseindia.com/option-chain"
let url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
let headers = {
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
  'accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'
}

const instance = axios.create({
  baseURL: url_oc,
  headers: headers,
  cookie: cookie ? cookie : ""
});



const getCookies = async () => {
  try {
    const response = await instance.get(url_oc);
    cookie = response.headers['set-cookie'].join();
  } catch (error) {
    if (error.response.status === 403) {
      console.log("getCookies =========> error.status === 403");
      await getCookies()
    } else {
      console.log("getCookies =========> error");
    }
  }
}


const getAPIData = async () => {
  try {
    if (cookie) {
      const response = await instance.get(url);
      console.log(response.data.records.timestamp);
    }

  } catch (error) {
    if (error.response && error.response.status === 401) {
      console.log("getAPIData =========> error.status === 401");
      if (!cookie) {
        console.log("getAPIData =========> cookie not found");
        await getCookies()
      }
      await getAPIData()
    } else {
      console.log("getAPIData =========> error");
    }
  }
}



(async () => {
  setInterval(async () => {
    await getCookies()
  }, 5000);

  setInterval(async () => {
    await getAPIData()
  }, 3000);
})()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM