Created
January 26, 2017 13:26
-
-
Save andrealmar/0caab3e2975f27f3f58bc53d60cbd2f2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 json | |
import logging | |
import os | |
from pathlib import Path | |
from urllib.request import urlopen, Request | |
logger = logging.getLogger(__name__) | |
types = {'image/jpeg', 'image/png'} | |
def get_links(client_id): | |
headers = {'Authorization': 'Client-ID {}'.format(client_id)} | |
req = Request('https://api.imgur.com/3/gallery/random/random/', headers=headers, method='GET') | |
with urlopen(req) as resp: | |
data = json.loads(resp.read().decode('utf-8')) | |
return [item['link'] for item in data['data'] if 'type' in item and item['type'] in types] | |
def download_link(directory, link): | |
download_path = directory / os.path.basename(link) | |
with urlopen(link) as image, download_path.open('wb') as f: | |
f.write(image.read()) | |
logger.info('Downloaded %s', link) | |
def setup_download_dir(): | |
download_dir = Path('images') | |
if not download_dir.exists(): | |
download_dir.mkdir() | |
return download_dir |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment