python - 为什么我的抓取 NSE 网站的程序在服务器中被阻止,但在本地却可以运行?

标签 python python-3.x

此 python 代码在本地计算机上运行,​​但未在 上运行

  1. digital ocean
  2. 亚马逊AWS
  3. Google 协作
  4. 赫罗库

以及许多其他 VPS。它在不同时间显示不同的错误。

import requests

headers = {
    'authority': 'beta.nseindia.com',
    'cache-control': 'max-age=0',
    'dnt': '1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
    'sec-fetch-user': '?1',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'none',
    'sec-fetch-mode': 'navigate',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9,hi;q=0.8',
}

params = (
    ('symbol', 'BANKNIFTY'),
)

response = requests.get('https://nseindia.com/api/quote-derivative', headers=headers, params=params)

#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.get('https://nseindia.com/api/quote-derivative?symbol=BANKNIFTY', headers=headers)

上面的代码有错误吗?我缺少什么?我从Chrome开发者工具>网络以隐身模式复制了头数据使用https://curl.trillworks.com/站点从curl命令生成python代码。

但是curl命令工作正常并且输出良好-

curl "https://nseindia.com/api/quote-derivative?symbol=BANKNIFTY" -H "authority: beta.nseindia.com" -H "cache-control: max-age=0" -H "dnt: 1" -H "upgrade-insecure-requests: 1" -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36" -H "sec-fetch-user: ?1" -H "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" -H "sec-fetch-site: none" -H "sec-fetch-mode: navigate" -H "accept-encoding: gzip, deflate, br" -H "accept-language: en-US,en;q=0.9,hi;q=0.8"  --compressed

为什么curl命令可以工作,但是curl命令生成的python却不能工作?

最佳答案

有两件事需要注意。

  1. 请求 header 需要包含“主机”和“用户代理”
__request_headers = {
        'Host':'www.nseindia.com', 
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0',
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 
        'Accept-Language':'en-US,en;q=0.5', 
        'Accept-Encoding':'gzip, deflate, br',
        'DNT':'1', 
        'Connection':'keep-alive', 
        'Upgrade-Insecure-Requests':'1',
        'Pragma':'no-cache',
        'Cache-Control':'no-cache',    
    }
  • 以下 Cookie 是动态设置的,需要动态获取和设置。
  • 'nsit',
    'nseappid',
    'ak_bmsc'
    

    这些是根据正在使用的功能从 nse 设置的。 这个例子:最大赢家/输家。 我试图获取最大赢家和输家列表,其中请求在没有这些 cookie 的情况下被阻止。

    try:
                nse_url = 'https://www.nseindia.com/market-data/top-gainers-loosers'
                url = 'https://www.nseindia.com/api/live-analysis-variations?index=gainers'
                resp = requests.get(url=nse_url, headers=__request_headers)
                if resp.ok:
                    req_cookies = dict(nsit=resp.cookies['nsit'], nseappid=resp.cookies['nseappid'], ak_bmsc=resp.cookies['ak_bmsc'])
                    tresp = requests.get(url=url, headers=__request_headers, cookies=req_cookies)
                    result = tresp.json()
                    res_data = result["NIFTY"]["data"] if "NIFTY" in result and "data" in result["NIFTY"] else []
                    if res_data != None and len(res_data) > 0:
                        __top_list = res_data
            except OSError as err:
                logger.error('Unable to fetch data')
    

    另一件事需要注意的是,NSE 会阻止来自大多数云虚拟机(例如 AWS、GCP)的这些请求。我可以从个人 Windows 计算机获取它,但不能从 AWS 或 GCP 获取。

    关于python - 为什么我的抓取 NSE 网站的程序在服务器中被阻止,但在本地却可以运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59740840/

    相关文章:

    python - 使用列表列表时出现 TypeError

    python - Pandas - 阅读 HTML

    python - 使用 CSV.QUOTE_NONNUMERIC 而不引用标题

    python-3.x - np.fft.fft 无法正常工作

    python-3.x - Visual Studio 代码错误 : Cannot read property 'then' of undefined

    python - Sphinx 中尖括号旁边的替换

    Python调试: How to step into another python scripts?

    python-3.x - Keras fit_generator(),这是正确的用法吗?

    python - 操作系统错误: [Errno 22] Invalid argument (Paramiko)

    python - 检索对象时包括整个外键对象