urllib文件下载

使用urllib 库来进行文件下载

根据网页的url,定义文件名filen进行文件保存

filename = urllib.urlretrieve(url = url, filename = filename, reporthook=reporthook)

定义一个reporthook 函数,用于记录下载百分比

def reporthook(self ,blocks_read, block_size, total_size):
    if not blocks_read:
        print "Connection opened"
        return
    if total_size < 0:
        print "Read %d blocks (%d bytes)" % (blocks_read, blocks_read * block_size)

    else:
        amount_read = blocks_read * block_size
        rate = float(amount_read)/(total_size)
        if rate >= 1.0:
            rating = 100
        else:
            rating = rate * 100
        sys.stdout.write("\rRead %d blocks, %d/%d, %.2f%%" % (blocks_read, amount_read, total_size, rating))
        sys.stdout.flush()

你可能感兴趣的:(urllib文件下载)