溫馨提示×

python怎么根據(jù)url下載圖片

小億
208
2024-03-22 14:45:42
欄目: 編程語言

你可以使用Python中的requests庫來下載圖片。以下是一個簡單的示例代碼:

import requests

def download_image(url, file_path):
    response = requests.get(url)
    if response.status_code == 200:
        with open(file_path, 'wb') as file:
            file.write(response.content)
            print(f"Image downloaded successfully to {file_path}")
    else:
        print("Failed to download image")

# 用法示例
url = "https://example.com/image.jpg"
file_path = "image.jpg"
download_image(url, file_path)

在上面的示例中,我們定義了一個download_image函數(shù)來下載圖片。你只需要傳入圖片的URL和保存的文件路徑作為參數(shù)調(diào)用該函數(shù)即可下載圖片。

0