python实现简单的下载url程序

import requests
import time

def downloadFile(name, url):
    headers = {'Proxy-Connection':'keep-alive'}
    r = requests.get(url, stream=True, headers=headers)
    length = float(r.headers['content-length'])
    f = open(name, 'wb')
    count = 0
    count_tmp = 0
    time1 = time.time()
    for chunk in r.iter_content(chunk_size = 512):
        if chunk:
            f.write(chunk)
            count += len(chunk)
            if time.time() - time1 > 2:
                p = count / length * 100
                speed = (count - count_tmp) / 1024 / 1024 / 2
                count_tmp = count
                print(name + ': ' + formatFloat(p) + '%' + ' Speed: ' + formatFloat(speed) + 'M/S')
                time1 = time.time()
    f.close()
    
def formatFloat(num):
    return '{:.2f}'.format(num)
    
if __name__ == '__main__':
    f=open('a.txt','r',encoding='utf-8')
    for a in f:
        print (a.split(',')[0].replace("'",''))
        downloadFile(a.split(',')[0].replace("'",''),a.split(',')[1].replace("'",'').strip()) #备注 原因:因为url没有去掉空格 导致
        #原因:360.exe本身就是字符 不需要前面再加'',然后这边downloadFile需要两个参数,而a本身只是一个参数,先通过split切分这一行字符为两串字符,然后填充进去即可


直接调用即可

你可能感兴趣的:(Python)