编码 - Python 3.6中 'utf-8' codec can't decode byte invalid start byte?

查看:659
本文介绍了编码 - Python 3.6中 'utf-8' codec can't decode byte invalid start byte?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

Python 3.6中,网页信息解析失败,试了很多种编码,查看网页的编码方式也是utf-8。
错误信息:'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte?
还有就是第一个print终端里打印出来的unicode内容是[b'\x1f\x8b\x08\x00\x...]这种格式的,之前也有过这种情况,一个print打2个变量,就是b'\x, 如果分来2行打又变回了汉字。是因为什么原因呢?

# -*- coding: utf-8 -*-
import json , sqlite3
import urllib.request

url = ('http://wthrcdn.etouch.cn/weather_mini?city=%E4%B8%8A%E6%B5%B7')
resp = urllib.request.urlopen(url)
content = resp.read()

print(content)
print(type(content))
print(content.decode('utf-8'))

解决方案

看了一下网站返回的是gzip压缩过的数据,所以要进行解码

# coding=utf-8
from io import BytesIO
import gzip
import urllib.request

url = ('http://wthrcdn.etouch.cn/weather_mini?city=%E4%B8%8A%E6%B5%B7')
resp = urllib.request.urlopen(url)
content = resp.read() # content是压缩过的数据

buff = BytesIO(content) # 把content转为文件对象
f = gzip.GzipFile(fileobj=buff)
res = f.read().decode('utf-8')
print(res)

这篇关于编码 - Python 3.6中 'utf-8' codec can't decode byte invalid start byte?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆