Download Multiple Images from URL List (Python 3)

Question:

I am trying to download many images from a list of URLs.
When I use this code on just one image, it works fine.

img = Image.open(requests.get(url_dict[key], stream = True).raw)
        img.save(f'images/{file_name}.jpg')

When I run it through the for loop below, it downloads a bunch of empty files with no extension.
Why?
How do I fix this?

for key in url_dict:
    file_name = key.replace(' ', '_')
    img = Image.open(requests.get(url_dict[key], stream = True).raw)
    img.save(f'images/{file_name}.jpg')

I am expecting to get a folder full of images that actually contain data.

Asked By: Squidly

||

Answers:

Try using the format of the pillow image to create the file.

I’ve tried this code with different URLs and worked ok for me.

import requests
from PIL import Image

url_dict = {"river":"https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Escudo_del_C_A_River_Plate.svg/1200px-Escudo_del_C_A_River_Plate.svg.png","river1":"https://play-lh.googleusercontent.com/LS7e70lkgIyJHxBWKr1YY5BRytD7Aw2th-dk8K66kU-c-fkr5e2Yo3Eh2RK9vFanYh8"}

for key in url_dict:
    file_name = key.replace(' ', '_')
    img = Image.open(requests.get(url_dict[key], stream = True).raw)
    img.save(f'images/{file_name}.{img.format.lower()}')
Answered By: Pedro Rocha