pythonurllibimagedownload

How to download an image to a specific local directory using either urllib or shutil?


I used shutil to download an image from an URL and it works fine but it downloads the images on the project directory. Is it possible to specify a directory so that the program saves it there?

I searched for a solution on StackOverflow but only found a solution using urllib urlretrieve which does not really relate to what I am trying to do. Thank you

import requests
import shutil
import os
import urllib.request

url = "https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/facelift_2019/homepage/families-gallery/2022/04_12/family_chooser_tecnica_m.png"

file_name = input("save image as :")
file_name += ".jpg"

res = requests.get(url, stream = True)
if res.ok:
    with open(file_name,"wb") as f:
        shutil.copyfileobj(res.raw,f)
    print("image succesfully downloaded ", file_name)
else:
    print("Download failed: status code {}\n{}".format(res.status_code, res.text))

or using urllib


f = open("sadasd.png", "wb")
f.write(urllib.request.urlopen(r"https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/facelift_2019/homepage/families-gallery/2022/04_12/family_chooser_tecnica_m.png").read())
f.close()


Solution

  • I found a simpler solution. So I changed my code to use only Urllib. What I was missing was the forward slash at the end of the destination path which is C:users\user\Pictures\test/.

    To add another piece of information as you can see in the code block urlretrieve uses the second argument as a location that you want to save.

    import urllib.request

    def download_jpg(url, file_path, file_name):
        full_path = file_path + file_name + ".jpg"
        urllib.request.urlretrieve(url, full_path)
    
    
    url = input("Enter img URL to download: ")
    file_name = input("Enter file name to save as: ")
    
    download_jpg(url, r"C:\Users\User\Pictures\test/", file_name )