Skip to content

Instantly share code, notes, and snippets.

@MoHD20 MoHD20/downloadXkcd
Created Jul 8, 2017

What would you like to do? - Downloads every single XKCD comic.
#! python3
# - Downloads every single XKCD comic.
# source: Automated the Boring Stuff with Python
import requests, os, bs4
url = '' # starting url
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
while not url.endswith('#'):
# Download the page.
print('Downloading page %s...' % url)
res = requests.get(url)
soup = bs4.BeautifulSoup(res.text, 'xml')
# Find the URL of the comic image.
comicElem ='#comic img')
if comicElem == []:
print('Could not find comic image.')
comicUrl = 'http://' + comicElem[0].get('src')[2:]
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
# Save the image to ./xkcd
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
# Get the Prev button's url.
prevLink ='a[rel="prev"]')[0]
url = '' + prevLink.get('href')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.