简体   繁体   中英

How do i download a image from a URL into a specific folder

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:)

Try this:

import urllib.request

urllib.request.urlretrieve('http://image-url', '/dest/path/file_name.jpg')

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)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM