You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用aiohttp调用猫咪图片API报错List of indices must be integers, not str求助

问题原因

两个接口返回的JSON结构存在差异:

  • 狗狗图片接口返回的是单JSON对象,包含link字段存储图片地址,原代码取值逻辑正确
  • 猫咪图片接口返回的是长度为1的数组,数组内的对象用url字段存储图片地址,你直接对数组取link字段不符合接口返回结构,所以触发报错
修复代码

将猫咪功能部分的set_image行代码修改为取数组第一项的url字段即可,完整修正代码如下:

if message.content.lower().startswith("!cat"):
    async with aiohttp.ClientSession() as session:
       request = await session.get('https://api.thecatapi.com/v1/images/search')
       catjson = await request.json()
    Catembed = discord.Embed(title="Kitty!", color=discord.Color.blue()) 
    Catembed.set_image(url=catjson[0]['url'])
    
    await message.channel.send(embed=Catembed)

小技巧:后续调试API相关代码时,可以先打印返回的JSON内容查看结构,能快速定位字段取值错误问题

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:15:06