Last active
June 14, 2018 09:58
-
-
Save impshum/73b4fae7375d05588e47f7e4a26fa0dd to your computer and use it in GitHub Desktop.
Download all xkcd comics
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
# Create a directory called comics next to the script first | |
import requests | |
n = 933 | |
while True: | |
if n == 404: | |
n += 1 | |
url = 'https://xkcd.com/{}/info.0.json'.format(n) | |
r = requests.get(url) | |
if r.status_code == 404: | |
break | |
d = r.json() | |
n = d['num'] | |
t = d['safe_title'] | |
u = d['img'] | |
print('{}: {}'.format(n, t)) | |
if u.endswith('.png'): | |
ext = 'png' | |
if u.endswith('.jpg'): | |
ext = 'jpg' | |
if u.endswith('.gif'): | |
ext = 'gif' | |
x = 'comics/{}-{}.{}'.format(n, t.replace(' ', '_').replace('/', '-'), ext) | |
with open(x, "wb") as f: | |
c = requests.get(u) | |
f.write(c.content) | |
n += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
8 LOC:
Long version, with makedir: