Python 3.X 报出 'utf-8' codec can't decode byte invalid start,pythondecode,Python 3.6中,
Python 3.X 报出 'utf-8' codec can't decode byte invalid start,pythondecode,Python 3.6中,
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 , sqlite3import urllib.requesturl = ('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'))
建议用requeset,代码如下:
import requestsr = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=%E4%B8%8A%E6%B5%B7')print(r.text)
看了一下网站返回的是gzip压缩过的数据,所以要进行解码
# coding=utf-8from io import BytesIOimport gzipimport urllib.requesturl = ('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)
requests不好用吗?
不是字符编码问题, 你看看你请求的 Respont headers
Status Code: 200 OK Access-Control-Allow-Headers: * Access-Control-Allow-Methods: * Access-Control-Allow-Origin: * Cache-Control: must-revalidate, max-age=300 Connection: Keep-Alive Content-Encoding: gzip Content-Length: 443 Date: Fri, 10 Mar 2017 03:20:46 GMT Fw-Cache-Status: hit Fw-Via: HTTP MISS from 58.59.19.99, DISK HIT from 183.131.161.27 Server: Tengine/2.1.2
是gzip, 如果用标准库的东西, 还需要把gzip 给解开
编橙之家文章,
相关内容
- Python类NameError出现原因,python类nameerror,报的错如下:
- 国外IP用VPN访问YouTube网页显示中文正常吗?,vpnyoutube,使
- Python能查到被导入而没有引用的类库吗,python类库,例:
- 易信公众帐号获取用户基本信息是通过什么方式,易信
- 求教sqlalchemy模糊查询正确使用方法,sqlalchemy模糊查询
- 想要在flask数据库中修改指定用户的角色,要如何操作
- Python manage.py db upgrade语句使用问题,manage.pyupgrade,最近
- 用python 模拟表单提交,获取服务器的文件下载链接,
- Django 表单验证和错误提示找不到解决方法,django错误提
- 求python隐藏真实IP不被服务器检测到的方法,pythonip,需
评论关闭