[python]python several ways to download files

If your file is relatively small, you can use the following method

use urllib

import urllib.request

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

use 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)

 use wget

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

wget.download(url, out=path)

Large file downloads can use the following methods:

method one:

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)

 Method Two:

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)

Guess you like

Origin blog.csdn.net/FL1623863129/article/details/132426043