When python requests html data using gzip headers, the response content is garbled and cannot be decoded. pythongzip
1. Background
When using the urllib2 module to capture web data, if you want to use the request header, you can reduce the amount of data during transmission. The returned data is compressed by gzip. Directly following content. decode ("utf8"), decoding will result in exceptions and the actual encoding type of webpage data cannot be detected.
2. Problem Analysis
In an http request, if the request header contains "Accept-Encoding": "gzip, deflate", and the web server supports this, the returned data is compressed, the advantage is that the network traffic is reduced, and the client decompress the package at the client layer based on the header, and then decode the package. Urllib2 module, the obtained http response data is the raw data, which has not been decompressed, so this is the root cause of garbled code.
3. solution 3.1 Request header remove "Accept-Encoding": "gzip, deflate"
The fastest solution is to directly obtain decoded data. The disadvantage is that the transmission traffic will increase a lot.
3.2 use zlib module, decompress, and decode to obtain readable plaintext data.
This is also the solution used in this article.
4. source code parsing
The Code is as follows. This is a typical form. The code for submitting request data in post mode is based on python 2.7.
,
Code block
Code block syntax follows standard markdown code
#! /usr/bin/env python2.7import sysimport zlibimport chardetimport urllibimport urllib2import cookielibdef 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()
The following environments are required to use this script:
-Mac OS 10.9 +
-Python 2.7.x
Directory
Use[TOC]
To generate a directory:
- Problem background
- Problem Analysis
- Solution
- 1 Request header remove Accept-Encodinggzip deflate
- 2. decompress the package using zlib module and decode the readable plaintext data.
- Source code parsing