[python]python下载文件几种方法

如果您的文件比较小,可以采用下面的方法

使用urllib

import urllib.request

url = "http://example.com/video.mp4"
path = "downloaded_file.video"
urllib.request.urlretrieve(url, path)

使用requests

import requests
url = "http://example.com/video.mp4"
path = "downloaded_file.video"

r = requests.get(url)
with open(path, "wb") as code:
    code.write(r.content)

 使用wget

import wget
url = "http://example.com/video.mp4"
path = "downloaded_file.video"

wget.download(url, out=path)

大文件下载可以采用下面方法:

方法一:

import requests
def download_file(url, save_path):
    response = requests.get(url, stream=True, verify=False)
    response.raise_for_status()
    with open(save_path, 'wb') as file:
        for chunk in response.iter_content(chunk_size=8192):
            file.write(chunk)

 方法二:

import urllib2
def download_file_urllib(url,save_path)
    r = urllib2.Request(url)
    u = urllib2.urlopen(r)
    with open(save_path, 'w') as f:
        while True:
            tmp = u.read(1024)
            if not tmp:
                break
            f.write(tmp)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FL1623863129

你的打赏是我写文章最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值