Skip to main content
 首页 » 编程设计

python之无法解码 urlopen 的结果

2025年05月04日15jillzhang

我在 Python3 中有以下代码

import urllib.request 
f = urllib.request.urlopen("https://www.okcoin.cn/api/v1/trades.do?since=0") 
a = f.read()  # there is data here 
print(a.decode())  # error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte 

我可以获得 https://www.okcoin.cn/api/v1/trades.do?since=0 的可读结果在浏览器中。浏览器确认编码为UTF-8。

我错过了什么? 谢谢

请您参考如下方法:

使用wget 下载数据显示数据实际上是 用 gzip 压缩。所以你需要先解压它。有一个 gzip 应该有用的模块。

编辑:试试这个。

import urllib.request 
import gzip 
 
f = urllib.request.urlopen("https://www.okcoin.cn/api/v1/trades.do?since=0") 
a = f.read()  # there is data here 
 
uncompressed = gzip.decompress(a) 
print(uncompressed.decode())