使用python获取下载文件的速度

时间:2016-10-19 08:44:12

标签: python network-programming urllib

我正在使用请求lib来下载文件,我收到了很多信息。关于响应如:大小,类型和日期。但我需要获得下载速度并设置它的最大值和最小值。我怎么能下载速度?

以下是代码:

import requests
import sys


link = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"
file_name = "downloaded.png"
response = requests.get(link, stream=True)
with open(file_name, "wb") as f:
        print "Downloading %s" % file_name
        response = requests.get(link, stream=True)
        total_length = int(response.headers.get('content-length'))
        print response.headers["content-type"]
        print total_length / 1024, "Kb"
        print int(response.headers["Age"]) * (10 ** -6), "Sec"
        print response.headers["date"]

        if total_length is None: # no content length header
            f.write(response.content)
        else:
            dl = 0
            for data in response.iter_content(chunk_size=4096):
                dl += len(data)
                f.write(data)
                done = int(50 * dl / total_length)
                sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) )
                sys.stdout.flush()

这是输出:

Downloading downloaded.png
image/png
213 Kb
0.054918 Sec
Wed, 19 Oct 2016 08:43:47 GMT
[==================================================]

1 个答案:

答案 0 :(得分:1)

我刚刚添加了import timestart变量,并将sys.stdout.write行替换为:How to measure download speed and progress using requests?

import requests
import sys
import time


link = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"
file_name = "downloaded.png"
start = time.clock()
response = requests.get(link, stream=True)
with open(file_name, "wb") as f:
    print "Downloading %s" % file_name
    response = requests.get(link, stream=True)
    total_length = int(response.headers.get('content-length'))
    print response.headers["content-type"]
    print total_length / 1024, "Kb"
    print int(response.headers["Age"]) * (10 ** -6), "Sec"
    print response.headers["date"]

    if total_length is None: # no content length header
        f.write(response.content)
    else:
        dl = 0
        for data in response.iter_content(chunk_size=4096):
            dl += len(data)
            f.write(data)
            done = int(50 * dl / total_length)
            sys.stdout.write("\r[%s%s] %s bps" % ('=' * done, ' ' * (50-done), dl//(time.clock() - start)))
            sys.stdout.flush()