问题描述

在request header包含”Accept-Encoding”:”gzip, deflate”, 并且web服务器端支持,返回的数据是经过压缩的,这个好处是减少了网络流量,由客户端根据header,在客户端层解压,再解码。urllib2 module,获取的http response数据是原始数据,没有经过解压,这时打开是乱码。

解决方案

1. 移除gzip头

Request header移除”Accept-Encoding”:”gzip, deflate”,该方法是最快的方案,能直接得到可解码的数据,缺点是,传输流量会增加很多。

2. 使用zlib module

import zlib
html = zlib.decompress(httpcontent, 16+zlib.MAX_WBITS)
print html

zlib module会解压缩,然后解码,得到可读的明文数据。


donation