Created
April 5, 2014 22:57
-
-
Save 1995eaton/9999161 to your computer and use it in GitHub Desktop.
Imgur Album 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
#!/usr/bin/env python | |
# | |
# Usage ./main.py <imgur_album_url> | |
# | |
from requests import get | |
from re import sub | |
from sys import argv | |
from os import listdir, mkdir, chdir | |
API = "https://api.imgur.com/2/album/" | |
def parse_url(url): | |
res = sub(".*\/(a|gallery)\/", "", url)[:5] | |
if res == url or len(res) < 5: | |
return None | |
return res | |
def download_images(urls, album_id): | |
mkdir(album_id) | |
chdir(album_id) | |
for i in urls: | |
print("Downloading:", i) | |
image_name = sub(".*\/", "", i) | |
with open(image_name, "wb") as image: | |
req = get(i, stream=True) | |
for block in req.iter_content(1024): | |
if block: | |
image.write(block) | |
image.flush() | |
def get_image_list(album_id): | |
request_url = API + album_id + ".json" | |
res = get(request_url).json() | |
image_urls = [] | |
for i in res['album']['images']: | |
image_urls.append(i['links']['original']) | |
return image_urls | |
def main(): | |
if len(argv) < 2: | |
print("Error: argument required") | |
return | |
album_id = parse_url(argv[1]) | |
if album_id in listdir(): | |
print("Error: images already downloaded from this album") | |
return | |
if not album_id: | |
print("Error: entered URL is invalid") | |
return | |
image_list = get_image_list(album_id) | |
download_images(image_list, album_id) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment