您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将Unicode转换为ASCII且在Python中没有错误

将Unicode转换为ASCII且在Python中没有错误

使用类似的压缩gzip已变得非常流行(约73%的网站都在使用它,包括Google,YouTube,Yahoo,Wikipedia,Reddit,Stack OverflowStack Exchange Network网站等大型网站)。 如果你像原始答案中那样使用gzip压缩响应进行简单解码,则会收到类似以下错误

UnicodeDecodeError:'utf8'编解码器无法解码位置1的字节0x8b

为了解码gzpipped响应,你需要添加以下模块(在Python 3中):

import gzip
import io

然后,你可以像这样解析内容

response = urlopen("https://example.com/gzipped-ressource")
buffer = io.BytesIO(response.read()) # Use StringIO.StringIO(response.read()) in Python 2
gzipped_file = gzip.GzipFile(fileobj=buffer)
decoded = gzipped_file.read()
content = decoded.decode("utf-8") # Replace utf-8 with the source encoding of your requested resource

代码读取响应,并将字节放入缓冲区。然后,gzip模块使用GZipFile函数读取缓冲区。之后,可以将压缩后的文件再次读取为字节,最后将其解码为通常可读的文本。

python 2022/1/1 18:17:17 有616人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶