Skip to content

Instantly share code, notes, and snippets.

@duhaime
Created April 12, 2020 13:20
Show Gist options
  • Save duhaime/22180d7ad80183a9e912089fe1779728 to your computer and use it in GitHub Desktop.
Save duhaime/22180d7ad80183a9e912089fe1779728 to your computer and use it in GitHub Desktop.
Download Unsplash Images
import os, requests, json
q = 'recipe'
p = 0
imgs = []
out_dir = 'fetched-images'
if not os.path.exists(out_dir): os.makedirs(out_dir)
while True:
r = requests.get('https://unsplash.com/napi/search/photos?query={}&per_page=20&page={}'.format(q, p))
j = r.json()
print(p)
for i in j['results']:
try:
imgs.append({
'url': i['urls']['regular'],
'alt': i['alt_description'],
'likes': i['likes'],
'color': i['color'],
})
except Exception as exc:
print(p, exc)
if p < j['total_pages']:
p += 1
else:
break
# write images
for i in imgs:
guid = i['url'].split('/')[-1].split('?')[0]
print(guid)
open(out_dir + '/' + guid + '.jpg', 'wb').write(requests.get(i['url'], allow_redirects=True).content)
# save meta
with open('{}-meta.json'.format(q), 'w') as out:
json.dump(imgs, out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment