跳轉到內容

Python 3:檔案和數字資產/檔案/下載

來自華夏公益教科書

下載檔案

[編輯 | 編輯原始碼]

安裝包

[編輯 | 編輯原始碼]

在 Jupyter 中

[編輯 | 編輯原始碼]
%pip install requests
%pip install pillow

在命令終端中

[編輯 | 編輯原始碼]

如果您使用的是來自作業系統的命令終端。您可以透過編寫以下命令來下載所需的軟體包

pip install requests
pip install pillow


Python 指令碼

[編輯 | 編輯原始碼]
from requests import get as http_get_requests
from PIL import Image
from io import BytesIO

url_to_image: str = 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/30/Stepper_Motor%2C_Model_17HS4401N%2C_4.jpg/1024px-Stepper_Motor%2C_Model_17HS4401N%2C_4.jpg'

headers = {
    'User-Agent': 'Download tutorial([link]; [email])'
}

response = http_get_requests(
    url_to_image, 
    headers=headers
)
content_type: str = response.headers['content-type']
content_length: int = int(response.headers['content-length'])

# Desired location to save the file
save_at: str = '/mnt/c/Users/Kentv/Desktop/test/test.jpg'
with Image.open(
    BytesIO(
        response.content
    )
) as image:
    image.save(save_at)
華夏公益教科書