如何使用Python aiohttp从OpenTDB API返回结果中提取question字段
解决方案
问题原因
你的代码存在两个核心错误:
- 你对
questionjson['results']执行了str()强制类型转换,将原本的列表类型转成了普通字符串,完全失去了结构化数据的键值读取能力 - OpenTDB返回的
results字段是列表类型,哪怕你只请求1道题(amount=1),题目数据也会包裹在列表的第一个元素中,不能直接对results取question键
修正后的代码
import html # 可选,用于转义API返回的HTML实体(比如'转成普通单引号) import random import aiohttp import discord # 你的业务逻辑部分 async with aiohttp.ClientSession() as session: request = await session.get('https://opentdb.com/api.php?amount=1&category=9&difficulty=hard') questionjson = await request.json() # 先判断响应是否正常,避免运行报错 if questionjson.get('response_code') == 0 and questionjson.get('results'): # 取results列表的第一个元素,再提取question字段 question_raw = questionjson['results'][0]['question'] # 可选:把HTML实体转成正常可显示的字符 question = html.unescape(question_raw) embed = discord.Embed(title="**__Trivia Time !!__**", description=question, color=random.choice(colors)) else: # 异常处理逻辑,可根据需求自定义提示 embed = discord.Embed(title="获取题目失败", description="请稍后重试", color=0xff0000)
补充说明
如果需要同时提取正确答案、错误选项等其他字段,同理对questionjson['results'][0]取对应键名即可,比如correct_answer = html.unescape(questionjson['results'][0]['correct_answer'])。
内容的提问来源于stack exchange,提问作者Atiksh Kundu
相关产品推荐
相关产品推荐

