Skip to content

Instantly share code, notes, and snippets.

@ChlorideCull
Last active December 24, 2015 23:39
Show Gist options
  • Save ChlorideCull/6881698 to your computer and use it in GitHub Desktop.
Save ChlorideCull/6881698 to your computer and use it in GitHub Desktop.
Was bored during class, wrote a XKCD parsing script to give you the URL, Name and Title of the specified (or current) comic. Also contains an option to only print the URL so you can pipe it into stuff.
#!/usr/bin/env python3
from urllib import request
import argparse
def format_text(text_input):
return text_input.replace("'", "'")
parser = argparse.ArgumentParser(description="Grab the URL to the specified XKCD comic.")
parser.add_argument('-c', '--comic', type=int, help="Specify a comic, or do not specify for the latest comic")
parser.add_argument('-u', '--url-only', action='store_true', help="Only print the URL, useful for piping")
args = parser.parse_args()
if args.comic != None:
xkcd = request.urlopen("http://xkcd.com/" + str(args.comic), data=None)
else:
xkcd = request.urlopen("http://xkcd.com/", data=None)
xkcd = xkcd.readlines()
for code in xkcd:
if "imgs.xkcd.com/comics" in str(code):
code = str(code).split('"')
if args.url_only != True:
print("Comic '" + format_text(code[5]) + "'")
print("Title: \"" + format_text(code[3]) + "\"")
print("")
print(code[1])
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment