html中压缩过的数据处理

要是爬取的内容被压缩过就

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from StringIO import StringIO
import urllib2
import gzip

# 有些网站不管客户端支不支持gzip解压缩,都会返回经过gzip压缩后的数据,比如 www.qq.com

headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"}
request = urllib2.Request("http://www.qq.com/", headers = headers)
response = urllib2.urlopen(request)
html = ""

# 判断:
# 如果响应信息里Content-Encoding 为gzip,表示响应内容通过gzip进行了压缩,则对数据进行解压缩处理
if response.info().get('Content-Encoding') == 'gzip':
    # 通过StringIO 获取压缩字节流数据 存入内存
    data = StringIO(response.read())
    # 通过gzip.GzipFile 来解压数据,返回解压后的文件对象
    f = gzip.GzipFile(fileobj = data)
    # 保存解压后的字符串
    html = f.read()
# 否则直接读取响应数据
else:
    html = response.read()

# 将数据写入到磁盘文件
with open("qq.html", "w") as f:
    f.write(html)

 

posted @ 2017-06-28 12:52  严恩娜  阅读(299)  评论(0编辑  收藏  举报