Python mechanize gzip response handling

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 gzip
		gz = 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()

 

你可能感兴趣的:(html,python,Yahoo,import,documentation,browser)