使用来自 BSE API 的 Python 请求迭代具有未知页数的分页数据
Iterating over paginated data with an unknown number of pages with Python requests from BSE API
我正在尝试从使用分页的 URL 中获取数据。我使用以下有效负载获取分页数据:
payload = {
'Pageno': '7',
'strCat': '-1',
'strPrevDate': '20220122',
'strScrip': '',
'strSearch': 'P',
'strToDate': '20220122',
'strType': 'C'}
不知道有多少页。我想一个接一个地处理它们,直到我得到一个不存在的页面。提取数据的代码如下:
jsonData = requests.get(url, headers=headers, params=payload).json()
我如何才能确保此请求以 URL 的存在为条件?
URL是:
url = 'https://api.bseindia.com/BseIndiaAPI/api/AnnGetData/w'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
BSE 的 API 将 return 200 OK 对于 Pageno
的任何正值,即使您已经阅读了数据末尾。您应该遍历每个页面,然后在遇到空列表(表示您已到达数据末尾)时中断。
import requests
payload = {
'Pageno': 1,
'strCat': '-1',
'strPrevDate': '20220122',
'strScrip': '',
'strSearch': 'P',
'strToDate': '20220122',
'strType': 'C'
}
url = 'https://api.bseindia.com/BseIndiaAPI/api/AnnGetData/w'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
data = []
should_fetch_next_page = True
while should_fetch_next_page:
print(f"Fetching page {payload['Pageno']} ...")
jsonData = requests.get(url, headers=headers, params=payload).json()
if jsonData["Table"]:
data.extend(jsonData["Table"])
payload['Pageno'] += 1
else:
should_fetch_next_page = False
print(data)
我正在尝试从使用分页的 URL 中获取数据。我使用以下有效负载获取分页数据:
payload = {
'Pageno': '7',
'strCat': '-1',
'strPrevDate': '20220122',
'strScrip': '',
'strSearch': 'P',
'strToDate': '20220122',
'strType': 'C'}
不知道有多少页。我想一个接一个地处理它们,直到我得到一个不存在的页面。提取数据的代码如下:
jsonData = requests.get(url, headers=headers, params=payload).json()
我如何才能确保此请求以 URL 的存在为条件?
URL是:
url = 'https://api.bseindia.com/BseIndiaAPI/api/AnnGetData/w'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
BSE 的 API 将 return 200 OK 对于 Pageno
的任何正值,即使您已经阅读了数据末尾。您应该遍历每个页面,然后在遇到空列表(表示您已到达数据末尾)时中断。
import requests
payload = {
'Pageno': 1,
'strCat': '-1',
'strPrevDate': '20220122',
'strScrip': '',
'strSearch': 'P',
'strToDate': '20220122',
'strType': 'C'
}
url = 'https://api.bseindia.com/BseIndiaAPI/api/AnnGetData/w'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
data = []
should_fetch_next_page = True
while should_fetch_next_page:
print(f"Fetching page {payload['Pageno']} ...")
jsonData = requests.get(url, headers=headers, params=payload).json()
if jsonData["Table"]:
data.extend(jsonData["Table"])
payload['Pageno'] += 1
else:
should_fetch_next_page = False
print(data)