Skip to content

Added automation script for downloading xkcd comics #867

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions xkcd_downloader/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## XKCD Comics downloader

A Python script to download the latest XKCD comics.

To run the script, go to the directory in bash,

1. Run the script
```bash
python3 download_xkcd.py url_to_the_comic
```

2. The comics will be downloaded in the same directory as the script.
33 changes: 33 additions & 0 deletions xkcd_downloader/download_xkcd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#! python3

import requests
import os
import bs4

url = input("The url of the XKCD comics") # starting url
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
while not url.endswith('#'):
print('Downloading page %s...' % url)
res = requests.get(url)
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, 'html.parser')
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = 'https:' + comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()

# Get the Prev button's url.
prevLink = soup.select('a[rel="prev"]')[0]
url = 'https://xkcd.com' + prevLink.get('href')

print('Done.')