11#! python2
22# xkcd.py - Downloads comics from xkcd.com.
33#
4- # Takes 2 optional arguments when launched from the command line
5- # which in default are "download=latest" and
6- # "path=C:\XKCD"
7- #
8- # 'download' argument specifies whether to download the 'latest' or
9- # 'all' XKCD comics
10- # Using "latest" will download all the comics published since you
11- # the last comic you downloaded. If no prior comics have been downloaded,
12- # only the most recent comic will be downloaded.
13- #
14- #
15- # 'path' argument specifies the path where to save the comics
164
175# Standard library modules
186import os , sys , ConfigParser , argparse , logging
3220 format = '%(levelname)s:%(message)s' )
3321
3422def create_config ():
23+ """ Function used to create the configuration file
24+ if it does not exist in the program's path.
25+
26+ It returns a ConfigParser object
27+ """
3528 config = ConfigParser .ConfigParser ()
3629 config .add_section ('Defaults' )
3730 config .set ('Defaults' , 'path' , 'C:\\ XKCD' )
@@ -42,6 +35,9 @@ def create_config():
4235 return config
4336
4437def get_args ():
38+ """ Function that parses the command line arguments and returns
39+ them in a argparse.Namespace object
40+ """
4541 if not os .path .lexists ('xkcd.cfg' ):
4642 config = create_config ()
4743 else :
@@ -116,6 +112,9 @@ def main():
116112 comics = []
117113 initial = None
118114 final = None
115+
116+ # Reading the log file to check the previously downloaded
117+ # comics
119118 with open ('xkcd.log' , 'rb' ) as fin :
120119 for line in fin .readlines ():
121120 x = line .split (':' )
@@ -129,8 +128,8 @@ def main():
129128 second = i .split ('--' )[1 ]
130129 if initial == None or first < initial :
131130 initial = int (first )
132- elif final != '#' and final == None or second == '#' or second > final :
133- end = second
131+ if final != '#' and final == None or second == '#' or second > final :
132+ final = second
134133
135134 try :
136135 if 'comic_number' in keys :
@@ -170,18 +169,18 @@ def download_comic(start='1', end='#'):
170169 url = 'http://xkcd.com/{0}' .format (start )
171170
172171 while not url .endswith (end ):
173-
172+ # Getting the webpage
174173 res = get_resource (url )
175174
176175 soup = bs4 .BeautifulSoup (res .text , "html.parser" )
177176
178177 if CURRENT_COMIC == '' :
179178 CURRENT_COMIC = os .path .split (url )[1 ]
180179
181- # Getting the url for the image.
182180 comicElem = soup .select ('#comic img' )
183181 if len (comicElem ) > 0 :
184182 try :
183+ # Getting the url for the image.
185184 comicurl = 'http:{0}' .format (comicElem [0 ].get ('src' ))
186185
187186 # Download and save the image
0 commit comments