1

I've been trying to write a function that receives a list of URLs and downloads each image from each URL to a given folder. I understand that I am supposed to be using the urlib library but I am not sure how.. the function should start like this :

def download_images(img_urls, dest_dir):

I don't even know how to start and could only find information online on how to download an image but not into a specific folder. If anyone can help me understand how to do the above, it would be wonderful.

thank you in advance:)

Rotemika
  • 61
  • 3
  • you are supposed to use [requests](https://pypi.org/project/requests/) library not urllib – Vaibhav Vishal Nov 12 '19 at 14:27
  • Break up the problem: Figure out how to access a URL, then figure out how to get an image from there, then figure out how to save that image to a folder. [OpenCV](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html) is a good module for loading and saving images. – mattrea6 Nov 12 '19 at 14:28
  • Does this answer your question? [How to save an image locally using Python whose URL address I already know?](https://stackoverflow.com/questions/8286352/how-to-save-an-image-locally-using-python-whose-url-address-i-already-know) – Maurice Meyer Nov 12 '19 at 14:29
  • Check out this SO thread with a similar question, using urllib: https://stackoverflow.com/questions/3042757/downloading-a-picture-via-urllib-and-python – eppe2000 Nov 12 '19 at 14:31

3 Answers3

2

Try this:

import urllib.request

urllib.request.urlretrieve('http://image-url', '/dest/path/file_name.jpg')
Manualmsdos
  • 1,505
  • 3
  • 11
  • 22
Meroz
  • 859
  • 2
  • 8
  • 28
1

You can use requests library, for example:

import requests

image_url = 'https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png'
try:
    response = requests.get(image_url)  
except:
    print('Error')    
else:
    if response.status_code == 200:
        with open('stackoverflow-1.png', 'wb') as f:
            f.write(response.content)
Manualmsdos
  • 1,505
  • 3
  • 11
  • 22
1

Here it's a simple solution for your problem using urllib.request.urlretrieve for download the image from your url list img_urls and os.path.basename to get the file name from the url so you can save it with its original name in your dest_dir

from urllib.request import urlretrieve
import os

def download_images(img_urls, dest_dir):
    for url in img_urls:
        urlretrieve(url, dest_dir+os.path.basename(url))

giague
  • 11
  • 2