如何使用aiohttp和discordy.py读取API响应的所有页面



我正在使用discord.py重写和aiohttp。这个API的文档非常少,从我所看到的来看,我还没有看到;next_page";链接响应中的任何位置。

如何使json响应的所有页面在执行查询时都被考虑,而不仅仅是默认的第一页?

这是我目前的相关代码:

async def command(ctx, *, name):
if not name:
return await ctx.channel.send('Uhhhh. How am I supposed to show you info if you don't enter a name?')
async with ctx.channel.typing():
async with aiohttp.ClientSession() as cs:
async with cs.get("https://website.items.json") as r:
data = await r.json()
listings = data["items"]
for k in listings:
if name.lower() == k["name"].lower():
await ctx.channel.send("message with results and player info as ascertained in the above code")```

您只需获取最大页数并对其进行迭代。最终的url如下所示。

https://theshownation.com/mlb20/apis/items.json?page=2

以下是如何设置环路

for page_number in range(1,total_pages):
url = f'https://theshownation.com/mlb20/apis/items.json?page={page_number}'

编辑:

完整的实现是这样的。

@bot.command()
async def card(ctx, *, player_name):
if not player_name:
return await ctx.channel.send('Uhhhh. How am I supposed to show you player info if you don't enter a player name?')
async with ctx.channel.typing():
async with aiohttp.ClientSession() as cs:
for page_number in range(1, 20):
async with cs.get(f"https://theshownation.com/mlb20/apis/items.json?page={page_number}") as r:
data = await r.json()
print(data["page"])
listings = data["items"]
for k in listings:
if player_name.lower() == k["name"].lower():
return await ctx.channel.send("message with results and player info as ascertained in the above code")

await ctx.send('Sorry could not find him')

最新更新