Skip to main content

Download Images From Flickr Set

Uses flickrapi which is in pypi to facilitate downloading all the images in a flickr set. When calling from the command line give the arguments username, set, and folder to save in. Example, python download_flickr_sets.py username 'Favorites of Peru' peru Will save all the images of username's "Favorites of Peru' in the peru directory.

text/x-python download_flickr_sets.py — 2 KB

File contents

API_KEY = "XXX"
API_KEY_SECRET = "XXX"
import flickrapi
import sys, urllib, os

flickr = flickrapi.FlickrAPI(API_KEY, API_KEY_SECRET)

def getPhotoSetId(user_id, theset):
    
    sets = flickr.photosets_getList(user_id=user_id)
    
    for photoset in sets.photosets[0].photoset:
        if photoset.title[0].text == theset or photoset['id'] == theset:
            return photoset['id']
            
    raise Exception("Can't find flickr set")

def getImageURL(photo):
    photo = flickr.photos_getInfo(photo_id=photo['id'], secret=photo['secret']).photo[0]
    
    return [
        "http://farm%s.static.flickr.com/%s/%s_%s%s.%s" % (
            photo['farm'], 
            photo['server'], 
            photo['id'],
            photo['originalsecret'],
            '_o',
            photo['originalformat']
        ),
        photo.title[0].text + "." + photo['originalformat']
    ]
    
def getUserId(user):
    id = None
    try:
        id = flickr.people_findByUsername(username=user).user[0]['nsid']
    except:
        try:
            id = flickr.people_getInfo(user_id=user).person[0]['nsid']
        except:
            raise Exception("Could Not Find User")
    
    return id
    
def downloadFlickrPhotosFromSet(user, photoset, folder):
    
    user_id = getUserId(user)
    photoset_id = getPhotoSetId(user_id, photoset)
    
    photos = flickr.photosets_getPhotos(
        user_id=user_id, 
        photoset_id=photoset_id,
        per_page=1000,
        page=1
    )
    
    photos = [image for image in photos.photoset[0].photo]
    
    if folder not in os.listdir('.'):
        os.mkdir(folder)
    
    totalimages = len(photos)
    count = 1
    
    for photo in photos:
        photo_info = getImageURL(photo)
        print "Downloading photo(%s/%s) '%s'" % (count, totalimages, photo_info[1])
        urllib.urlretrieve(photo_info[0], folder + '/' + photo_info[1])
        count = count + 1
        
# If called from the command line
if __name__=='__main__':
    downloadFlickrPhotosFromSet(sys.argv[1], sys.argv[2], sys.argv[3])