我想使用python(urllib或urllib2)从网站下载文件 在下载时我想显示下载的百分比。
#!usr/bin/env python
#-*- coding: latin1 -*-
import urllib
url = 'http://ww1.microchip.com/downloads/en/DeviceDoc/pk2cmdv1-20Linux2-6.tar.gz'
urllib.urlretrieve(url, "pickit.tar.gz")
我怎么能实现这个?
答案 0 :(得分:1)
以下代码应该有效:
def download(url, local_file):
def progress(blocks_read, block_size, total_size):
percent = min(int(blocks_read * block_size * 100 / total_size), 100)
sys.stdout.write("\rdownloading {}: {:2}%".format(local_file, percent))
if percent == 100:
sys.stdout.write('\n')
sys.stdout.flush()
urllib.urlretrieve(url, local_file, reporthook=progress)
# call download function
download("http://ww1.microchip.com/downloads/en/DeviceDoc/pk2cmdv1-20Linux2-6.tar.gz",
"pickit.tar.gz")
答案 1 :(得分:0)
使用“ urllib2.urlopen(..)”代替读取标题,它将包含您要查找的数据(内容长度)!
答案 2 :(得分:0)