Last active
December 5, 2018 00:53
-
-
Save zaknesler/d6775095db89748997e32d14d635de2e to your computer and use it in GitHub Desktop.
Unsplash collection downloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests, math, os | |
accessKey = 'insert_your_unsplash_access_key_here' | |
def main(): | |
print('\nUnsplash Collection Downloader\n') | |
collection = input('Enter collection id: ') | |
photos, directory = getPhotos(collection) | |
downloadPhotos(photos, directory) | |
def getPhotos(collection): | |
collectionUrl = f'https://api.unsplash.com/collections/{ collection }/?client_id={ accessKey }' | |
collectionResponse = requests.get(collectionUrl).json() | |
total = int(collectionResponse['total_photos']) | |
photos = [] | |
perPage = 30 | |
for page in range(1, math.ceil(total / perPage) + 1): | |
photosUrl = f'https://api.unsplash.com/collections/{ collection }/photos/?client_id={ accessKey }&per_page={ perPage }&page={ page }' | |
for photo in requests.get(photosUrl).json(): | |
photos.append([photo['id'], photo['urls']['raw']]) | |
return photos, collectionResponse['title'] | |
def downloadPhotos(photos, directory): | |
if not os.path.exists(directory): | |
os.makedirs(directory) | |
print() | |
for photo in photos: | |
print(f'\rDownloading photo { photos.index(photo) + 1 } of { len(photos) }... ', end = '', flush = True) | |
name = f'{ directory }/{ photo[0] }.jpg' | |
if os.path.exists(name): | |
return | |
file = open(name, 'wb') | |
file.write(requests.get(photo[1]).content) | |
file.close() | |
print('Done!\n') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment