繁体   English   中英

如何使用带有 discord.py 的 aiohttp 读取 API 响应的所有页面?

[英]How can I read all pages of an API response using aiohttp with discord.py?

我正在使用 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM