我正在编写一个应用程序,用于计算在网页上使用gzip后节省的成本。当用户输入使用gzip的网页的URL时,应用程序应该因gzip而节省大小。
我该如何解决这个问题?
这是我在页面上作为GET请求的标题获取的内容:
{
'X-Powered-By': 'PHP/5.5.9-1ubuntu4.19',
'Transfer-Encoding': 'chunked',
'Content-Encoding': 'gzip',
'Vary': 'Accept-Encoding',
'Server': 'nginx/1.4.6 (Ubuntu)',
'Connection': 'keep-alive',
'Date': 'Thu, 10 Nov 2016 09:49:58 GMT',
'Content-Type': 'text/html'
}
我正在使用requests
检索页面:
r = requests.get(url, headers)
data = r.text
print "Webpage size : " , len(data)/1024
答案 0 :(得分:3)
如果您已经下载了网址(使用requests
GET
请求但没有stream
选项,那么您已经拥有这两种尺寸,因为整个响应已下载并解压缩,并且标题中提供了原始长度:
from __future__ import division
r = requests.get(url, headers=headers)
compressed_length = int(r.headers['content-length'])
decompressed_length = len(r.content)
ratio = compressed_length / decompressed_length
您可以将Accept-Encoding: identity
HEAD请求内容长度标头与设置为Accept-Encoding: gzip
的标头进行比较:
no_gzip = {'Accept-Encoding': 'identity'}
no_gzip.update(headers)
uncompressed_length = int(requests.get(url, headers=no_gzip).headers['content-length'])
force_gzip = {'Accept-Encoding': 'gzip'}
force_gzip.update(headers)
compressed_length = int(requests.get(url, headers=force_gzip).headers['content-length'])
但是,这可能对所有服务器都不起作用,因为动态生成的内容服务器通常会在这种情况下使用Content-Length标头,以避免必须首先呈现内容。
如果您要请求chunked transfer encoding资源,则 内容长度标头,在这种情况下,HEAD请求可能会也可能不会为您提供正确的信息
在这种情况下,你有流整个响应并从流的末尾提取解压缩的大小(GZIP格式包含这个作为一个小端4字节无符号int at最后)。使用原始urllib3响应对象上的stream()
method:
import requests
from collections import deque
if hasattr(int, 'from_bytes'):
# Python 3.2 and up
_extract_size = lambda q: int.from_bytes(bytes(q), 'little')
else:
import struct
_le_int = struct.Struct('<I').unpack
_extract_size = lambda q: _le_int(b''.join(q))[0]
def get_content_lengths(url, headers=None, chunk_size=2048):
"""Return the compressed and uncompressed lengths for a given URL
Works for all resources accessible by GET, regardless of transfer-encoding
and discrepancies between HEAD and GET responses. This does have
to download the full request (streamed) to determine sizes.
"""
only_gzip = {'Accept-Encoding': 'gzip'}
only_gzip.update(headers or {})
# Set `stream=True` to ensure we can access the original stream:
r = requests.get(url, headers=only_gzip, stream=True)
r.raise_for_status()
if r.headers.get('Content-Encoding') != 'gzip':
raise ValueError('Response not gzip-compressed')
# we only need the very last 4 bytes of the data stream
last_data = deque(maxlen=4)
compressed_length = 0
# stream directly from the urllib3 response so we can ensure the
# data is not decompressed as we iterate
for chunk in r.raw.stream(chunk_size, decode_content=False):
compressed_length += len(chunk)
last_data.extend(chunk)
if compressed_length < 4:
raise ValueError('Not enough data loaded to determine uncompressed size')
return compressed_length, _extract_size(last_data)
演示:
>>> compressed_length, decompressed_length = get_content_lengths('http://httpbin.org/gzip')
>>> compressed_length
179
>>> decompressed_length
226
>>> compressed_length / decompressed_length
0.7920353982300885
答案 1 :(得分:0)
在接受和不接受gzip压缩的情况下发送HEAD请求,并在结果之间比较Content-Length标头。
'accept-encoding'标头可以帮助您使用gzip压缩请求:
'accept-encoding': 'gzip'
在这种情况下,请求不使用gzip编码。
'accept-encoding': ''
requests库可以轻松处理发送HEAD请求:
import requests
r = requests.head("http://stackoverflow.com/", headers={'Accept-Encoding': 'gzip'})
print(r.headers['content-length'])
41450
r = requests.head("http://stackoverflow.com/", headers={'Accept-Encoding': ''})
print(r.headers['content-length'])
250243