Bạn có thể download file (File ảnh, File text, …) từ 1 đường dẫn trên web sử dụng thư viện urllib của Python 3.
Đoạn source code Python 3 như sau:
import urllib
import os
output_dir = '/tmp'
image_url = 'https://vinasupport.com/assets/img/vinasupport_logo.png'
# Make output directory if not exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# save path
image_save_path = output_dir + '/' + os.path.basename(image_url)
# Download file from url
urllib.request.urlretrieve(image, image_save_path)
print(image_save_path)
Trong ví dụ trên, mình thực hiện download file ảnh có đường dẫn là: https://vinasupport.com/assets/img/vinasupport_logo.png
Và lưu nó xuống dường dẫn trên server /tmp/vinasupport_logo.png
Một cách khác là sử dụng thư viện requests
Đầu tiên cài đặt requests thông qua trình quản lý module / packages của Python 3
pip install requests
Sử dụng requests để download file:
from requests import get # to make GET request
def download(url, file_name):
# open in binary mode
with open(file_name, "wb") as file:
# get request
response = get(url)
# write to file
file.write(response.content)
Nguồn: vinasupport.com