解析网页抓取所得gzip压缩数据

在进行网页数据抓取时,会遇到压缩数据,可能主要出于如下考虑:

  1. 简单的防抓取方法

    没有经过分析就对抓取的网页内容直接进行文本解析,肯定会遇到问题,就像我开始的时候一样。。。

  2. 压缩数据减少流量

    这个一般用于提供数据接口,将数据压缩后可以大大减少流量

以下提供对抓取数据的处理方法:

  1. 检测反馈内容是否压缩,并对压缩内容解压

  2. 检测数据文本编码格式,解压后返回unicode文本

检测编码格式所用工具:chardet

# -*- coding: utf-8 -*-

import gzip, StringIO, codecs, chardet
from utils import *

def getEncoding(txt):
    """ 检查文本内容的编码方式
    """
    try:
        coding = chardet.detect(txt)['encoding']

        if 'None' == coding:
            return None
        else:
            return coding

    except Exception as ex:
        print 'fail getEncoding {0}'.format(ex)
        return None

def readResponse(resp):
    """ 读取网页抓取返回内容
    """
    if resp.getcode() == 200:
        encoding = resp.headers.get('Content-Encoding')

        info = resp.read()

        if('gzip' == encoding):
            print 'read response compress gzip'
            try:
                gf = gzip.GzipFile(fileobj=StringIO.StringIO(info), mode="r")
                info = gf.read()
            except Exception as ex:
                print 'fail read response, gzip'
                info = ''

    if info!='':
        # 删除BOM头
        info = info.strip(codecs.BOM_UTF8)
        code = getEncoding(info)
        if code:
            info = info.decode(code)
            print 'read response, encoding {0}'.format(code)
        else:
            print 'fail parse text encode'

    return info

参考链接:

  1. Handling compressed data
  2. 关于 Content-Encoding: gzip

 Jun 6th, 2013  python

原创文章,版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值