Python mechanize gzip response handling

来源:互联网 发布:好听的编程项目名称 编辑:程序博客网 时间:2024/05/18 03:09

http://unformatt.com/news/python-mechanize-gzip-response-handling/

Mechanize is awesome. The documentation is shit. The gzip support is non-existent. Some sites like Yahoo! require gzip support.

def ungzipResponse(r,b):headers = r.info()if headers['Content-Encoding']=='gzip':import gzipgz = gzip.GzipFile(fileobj=r, mode='rb')html = gz.read()gz.close()headers["Content-type"] = "text/html; charset=utf-8"r.set_data( html )b.set_response(r)b = Browser()b.addheaders.append( ['Accept-Encoding','gzip'] )r = b.open('http://some-gzipped-site.com')ungzipResponse(r,b)print r.read()