【问题标题】:Is there a way to resolve FORBIDDEN FOR url? [duplicate]有没有办法解决 FORBIDDEN FOR url? [复制]
【发布时间】:2021-01-11 05:34:31
【问题描述】:
import requests
from bs4 import BeautifulSoup
url = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY"

headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) chrome/85.0.4183.102 Safari/537.36','Accept-Language': 'en-US,en;q=0.9,hi;q=0.8,es;q=0.7','Accept-Encoding': 'gzip, deflate, br'}

response.raise_for_status()
df = response.json()

这曾经可以工作,但现在出现此错误 HTTPError: 401 Client Error: Unauthorized for url: https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY.

知道我应该怎么做才能在 python 中访问网站吗?

【问题讨论】:

  • 不,这个错误是完全不同的和新的。我无法在 python 中请求这个网站,但是当我在 chrome 中粘贴相同的链接时,它可以工作
  • 检查下面的答案。

标签: python html http beautifulsoup python-requests


【解决方案1】:

那么,我们应该访问main页面获取Cookies,然后联系API:

import requests

params = {
    'symbol': 'BANKNIFTY'
}

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0'
}


def main(url):
    with requests.Session() as req:
        req.headers.update(headers)
        r = req.get("https://www.nseindia.com")
        r = req.get(url, params=params).json()
        print(r)


main("https://www.nseindia.com/api/option-chain-indices")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 2016-07-10
    • 2011-06-27
    • 2020-09-16
    • 2012-08-21
    • 2020-12-13
    • 1970-01-01
    相关资源
    最近更新 更多