首页 > 解决方案 > 更改查询参数在 REST GET API 调用中引发 405 错误

问题描述

我正在尝试通过 Python 模拟该网站在调用典型安全性时进行的 REST API 调用(尝试这些选择:获取历史数据:“安全性价格量和数据的可交付头寸”,输入符号:“LaurusLabs”,选择系列:“全部”,选择时间段:22-01-2021 至 10-02-2021)

这是我的代码和修补的结果:

```python
import requests
from pprint import PrettyPrinter as pp
import urllib
printer = pp(indent=0)
headers = {
    "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",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
    "Dnt": "1",
    "Connection": "keep-alive",
    "Host": "www1.nseindia.com",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"}

session = requests.Session()
url_symb_count = "https://www1.nseindia.com/marketinfo/sym_map/symbolCount.jsp?symbol=LAURUSLABS"
response = requests.get(url_symb_count, headers = headers)
cookies = dict(response.cookies)
x = (response.text).strip()
#printer.pprint(cookies)

f = { "symbol": "LAURUSLABS","segmentLink": "3","symbolCount": 1,"series": "ALL","dateRange": " ","fromDate": "20-01-2021","toDate": "10-02-2021","dataType": "PRICEVOLUMEDELIVERABLE"}
url = 'https://www1.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?' + urllib.parse.urlencode(f)
response = session.get(url, headers = headers, cookies=cookies)
x = (response.text)
printer.pprint(x)
printer.pprint(url)

```

问题是每当我尝试查询不同的日期范围时,结果似乎都会给出状态 405 错误。事实上,这个链接似乎只适用于这个选择,但它是如何或为什么打败我的?

你能帮我解释一下为什么直接操纵日期会给我带来不同的结果吗?

标签: pythonjsonpython-requests

解决方案


所以我一直在玩这个半小时,这似乎一直在工作,每当我在我的 f 字典中改变时。


import requests
from pprint import PrettyPrinter as pp
import urllib

printer = pp(indent=2)
headers = {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en-US,en;q=0.5",
    "Connection": "keep-alive",
    "Dnt": "1",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36",
    "Host": "www1.nseindia.com",
    "Referer": "https://www1.nseindia.com/products/content/equities/equities/eq_security.htm",
    "Sec-GPC": "1",
    "X-Requested-With": "XMLHttpRequest"
}

f = {
    "symbol": "LAURUSLABS",
    "segmentLink": "3",
    "symbolCount": 1,
    "series": "ALL",
    "dateRange": " ",
    "fromDate": "04-05-2020",
    "toDate": "02-05-2021",
    "dataType": "PRICEVOLUMEDELIVERABLE"
}
url = 'https://www1.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?' + urllib.parse.urlencode(f)
response = requests.get(url, headers=headers)
x = (response.text)
printer.pprint(x)

   

编辑解释:

我只是在浏览 OP 提供的链接时观察了网络选项卡,并注意到所有请求都来自 "eq_security.htm" ,所以我只是复制了尽可能多的标题来匹配。我想可能是请求类型或日期格式,但事实并非如此。


推荐阅读