python urllib2是否会自动解压缩从网页获取的gzip数据? [英] Does python urllib2 automatically uncompress gzip data fetched from webpage?

查看:158
本文介绍了python urllib2是否会自动解压缩从网页获取的gzip数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

 data=urllib2.urlopen(url).read()

我想知道:

  1. 如何确定URL上的数据是否已压缩?

  1. How can I tell if the data at a URL is gzipped?

如果将urllib2压缩,是否会自动解压缩数据?数据将始终是字符串吗?

Does urllib2 automatically uncompress the data if it is gzipped? Will the data always be a string?

推荐答案

  1. 如何确定URL上的数据是否已压缩?

这将检查内容是否压缩并解压缩:

This checks if the content is gzipped and decompresses it:

from StringIO import StringIO
import gzip

request = urllib2.Request('http://example.com/')
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
    buf = StringIO(response.read())
    f = gzip.GzipFile(fileobj=buf)
    data = f.read()

  1. 如果将urllib2压缩,是否会自动解压缩数据?数据将始终是字符串吗?

不. urllib2不会自动解压缩数据,因为urllib2并未设置'Accept-Encoding'标头,而是由您使用:request.add_header('Accept-Encoding','gzip, deflate')

No. The urllib2 doesn't automatically uncompress the data because the 'Accept-Encoding' header is not set by the urllib2 but by you using: request.add_header('Accept-Encoding','gzip, deflate')

这篇关于python urllib2是否会自动解压缩从网页获取的gzip数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆