Python如何提取API返回JSON数据中的指定字段并打印
代码修改方案
你现有代码的核心问题是误用HTML解析库BeautifulSoup处理JSON格式的API响应,直接使用requests自带的JSON解析功能即可实现需求,具体调整如下:
- 移除不必要的
bs4依赖,减少安装成本 - 调用requests响应对象的
.json()方法,直接将返回的JSON字符串转为Python字典 - 从字典中按键取出指定字段直接打印即可
修改后的完整代码
try: import requests import os from urllib.parse import unquote # 用于解码用户名里的%20为正常空格,不需要可删除 except ImportError as ex: input(f"Module {ex.name} not installed, to install run '{'python' if os.name == 'nt' else 'python3.8'} -m pip install {ex.name}'\nPress enter to exit") exit() def main(): os.system('cls' if os.name == 'nt' else 'clear') print ("Input the userID below!") userID = str(input('~ ')) os.system('cls' if os.name == 'nt' else 'clear') URL = f"https://verify.eryn.io/api/user/{userID}" req = requests.get(URL) # 新增异常判断,避免请求失败时报错 if req.status_code != 200: print("请求失败,请检查输入的userID是否合法") os.system("pause") main() # 解析JSON为Python字典 res_data = req.json() # 单独打印指定字段 print(f"status: {res_data['status']}") print(f"robloxUsername: {unquote(res_data['robloxUsername'])}") print(f"robloxId: {res_data['robloxId']}") os.system("pause") main() if __name__ == "__main__": main()
补充说明
如果你不需要自动解码用户名中的%20,可以删除urllib.parse的导入,直接打印res_data['robloxUsername']即可。
内容的提问来源于stack exchange,提问作者Watz
相关产品推荐
相关产品推荐

