Python3执行base64解码后gzip解压触发TypeError参数类型错误
问题原因
- 报错的核心原因是你调用
b64decode()时传入的raw参数是字典类型,不符合base64解码要求的ASCII字符串/字节类输入要求 - 你从接口取到的
inv_contents字段本身就不是base64编码的字符串,它是已经结构化的字典:data字段存储的就是gzip压缩后的字节数组(里面的负数是有符号的字节值,需要转成无符号字节再处理),不需要额外做base64解码
修复后的代码
import requests from mojang import MojangAPI from pprint import pprint from gzip import decompress from io import BytesIO import json name = str(input("Enter your name of choice >>>")) api_key = "cant show you the key" uuid = MojangAPI.get_uuid(name) request_url = f"https://api.hypixel.net/player?key={api_key}&uuid={uuid}" hydata = requests.get(request_url).json() raw = hydata["player"]["stats"]["Pit"]["profile"]["inv_contents"] # 保存原始数据到文件(用json序列化代替直接转字符串,方便后续读取) with open("ProfessionalNames.json", 'w', encoding='utf-8') as f: json.dump(raw, f) # 直接处理data字段的字节数组,不需要base64解码 gzip_bytes = bytes([b & 0xff for b in raw["data"]]) decompressed_bytes = decompress(gzip_bytes) decoded = BytesIO(decompressed_bytes) pprint(decoded)
补充说明
- 原代码里多余的base64解码步骤已经删除,直接处理字典中
data字段的字节数组即可 - 转换字节时对负数做了无符号处理,符合gzip解压的输入要求
- 文件读写改用
with语法自动关闭文件,避免资源泄露
内容的提问来源于stack exchange,提问作者Gal
相关产品推荐
相关产品推荐

