如果您的文件比较小,可以采用下面的方法
使用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)