python3中UnicodeDecodeError: ‘utf8’ codec can’t decode问题的解决以及数据流解压缩问题
import urllib
from urllib import request
import gzip
首先,来看一个无法成功的请求
url = "http://www.baidu.com"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"Referer":"http://www.baidu.com",
"Connection":"keep-alive",
"Accept-Encoding":"gzip,deflate"
}
req = request.Request(url,headers = headers)
response = request.urlopen(req)
print(response)
html = response.read().decode("utf8")
print(html)
f = open("html.txt","wt",encoding = "utf8")
f.write(html)
f.close()
<http.client.HTTPResponse object at 0x0000020348091CC0>
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-42-41b32c4039b8> in <module>()
8 response = request.urlopen(req)
9 print(response)
---> 10 html = response.read().decode("utf8")
11 print(html)
12 f = open("html.txt","wt",encoding = "utf8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
这个请求无法成功,是因为headers中设置了Accept-Encoding参数,这个参数的存在,相当于告诉服务器,浏览器支持gzip压缩。因此,服务器就会在生成原生response后将其进行gzip压缩,而后把经过压缩的response返回给浏览器,浏览器对其进行解压缩。
因此,在这个案例中,返回的response其实是经过gzip压缩了的,所以无法直接用utf8进行解码。解决办法有如下两个:
1.删除Accept-Encoding参数,让服务器直接返回未经压缩的response
url = "http://www.baidu.com"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"Referer":"http://www.baidu.com",
"Connection":"keep-alive"
}
req = request.Request(url,headers = headers)
response = request.urlopen(req)
print(response)
html = response.read().decode("utf8")
print(html)
f = open("html.txt","wt",encoding = "utf8")
f.write(html)
f.close()
print("Thanks")
<http.client.HTTPResponse object at 0x00000203480BE320>
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
Thanks
2.在程序中进行解压
import gzip
from io import BytesIO
from urllib import request
url = 'http://www.baidu.com'
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"Referer":"http://www.baidu.com",
"Connection":"keep-alive",
"Accept-Encoding":"gzip"
}
req1 = request.Request(url,headers = headers)
response1 = request.urlopen(req1)
buffer1 = BytesIO(response1.read())
f_out1 = gzip.GzipFile(fileobj = buffer1,mode = "rb")
html = f_out1.read().decode("utf8")
print(html)
f = open("html333.txt","w",encoding = "utf8")
f.write(html)
f.close()
f_out1.close()
buffer1.close()
print("Thanks")
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
Thanks
关键的步骤在于:需要构建一个BytesIO对象,将response对象用read方法读取之后产生的字节数据对象放入其中,将之转化为一个“类文件对象”(file-simulated object),然后再将其传入GzipFile方法,构造一个新的gzip文件对象,对这个对象进行读取之后,就得到了解压后的字节数据对象,这时再对其进行decode解码就可以了。同样,这也是对http数据流的一个解压。
关于http数据流,网上是这样解释的:HTTP压缩是指: Web服务器和浏览器之间压缩传输的”文本内容“的方法。 HTTP采用通用的压缩算法,比如gzip来压缩HTML,Javascript, CSS文件。 能大大减少网络传输的数据量,提高了用户显示网页的速度。