python以gzip header请求html数据时,response内容乱码无法解码的解决方案

本文介绍了在使用urllib2模块抓取网页数据时遇到的gzip压缩问题,分析了其根本原因,并提供了两种解决方案:移除Accept-Encoding头部字段和使用zlib模块解压缩数据。通过代码示例展示了具体实现过程。

1. 问题背景

在使用urllib2 module抓取web数据时,如果希望使用如何request header,减少传输时数据量。返回的数据,是经过gzip压缩的。直接按照 content.decode(“utf8”), 解码会出现异常,并且也无法检测网页数据的实际编码类型。

2. 问题分析

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

3. 解决方案

3.1 Request header移除”Accept-Encoding”:”gzip, deflate”

最快的方案,能直接得到可解码的数据,缺点是,传输流量会增加很多。

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

这也是本文使用的方案

4. 源码解析

代码如下, 这是一个典型的模拟form表单,post方式提交请求数据的代码,基于python 2.7
,

代码块

代码块语法遵循标准markdown代码

#! /usr/bin/env python2.7
import sys
import zlib
import chardet
import urllib
import urllib2
import cookielib

def main():
    reload( sys )
    sys.setdefaultencoding('utf-8')
    url = 'http://xxx.yyy.com/test'
    values = {
            "form_field1":"value1",
            "form_field2":"TRUE",
             }

    post_data = urllib.urlencode(values)
    cj=cookielib.CookieJar()
    opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    headers ={"User-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0",
              "Referer":"http://xxx.yyy.com/test0",
              "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
              "Accept-Language":"en-US,en;q=0.5",
              "Accept-Encoding":"gzip, deflate",
              "Connection":"keep-alive",
              # "Cookie":"QSession=",
              "Content-Type":"application/x-www-form-urlencoded",
              }
    req = urllib2.Request(url,post_data,headers)
    response = opener.open(req)
    content = response.read()
    gzipped = response.headers.get('Content-Encoding')
    if gzipped:
        html = zlib.decompress(content, 16+zlib.MAX_WBITS)
    else:
        html = content
    result = chardet.detect(html)
    print(result)
    print html.decode("utf8")

if __name__ == '__main__':
    main()  

使用本脚本需要以下环境
- Mac OS 10.9+
- Python 2.7.x

目录

[TOC]来生成目录:

Python爬取网页,出现乱码的情况通常是由于编码问题引起的。常见的编码问题包括网页编码与解码方式不一致、网页编码与Python解码方式不一致等。解决这些问题的方法有很多,下面提供两种常用的解决方法。 方法一:指定网页编码方式 在爬取网页,可以通过requests库的encoding属性指定网页的编码方式,例如: ```python import requests url = 'http://www.example.com' response = requests.get(url) response.encoding = 'utf-8' # 指定编码方式为utf-8 html = response.text ``` 如果不确定网页的编码方式,可以使用chardet库自动检测编码方式,例如: ```python import requests import chardet url = 'http://www.example.com' response = requests.get(url) encoding = chardet.detect(response.content)['encoding'] # 自动检测编码方式 response.encoding = encoding html = response.text ``` 方法二:解压缩网页内容 有些网页的内容是经过压缩的,需要先解压缩才能正常显示。可以通过response.header中的content-encoding信息来确定使用哪个方式来解压解码,例如: ```python import requests import gzip import zlib url = 'http://www.example.com' response = requests.get(url) if response.headers.get('content-encoding') == 'gzip': html = gzip.decompress(response.content).decode('utf8') elif response.headers.get('content-encoding') == 'deflate': try: html = zlib.decompress(response.content, -zlib.MAX_WBITS).decode('utf8') except zlib.error: html = zlib.decompress(response.content).decode('utf8') else: html = response.text ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值