|
| 1 | +#! python3 |
| 2 | +# multidownloadXkcd.py - Downloads XKCD comics using multiple threads. |
| 3 | + |
| 4 | +import requests, os, bs4, threading |
| 5 | +os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd |
| 6 | + |
| 7 | +def downloadXkcd(startComic, endComic): |
| 8 | + for urlNumber in range(startComic, endComic): |
| 9 | + # Download the page. |
| 10 | + print('Downloading page http://xkcd.com/%s...' % (urlNumber)) |
| 11 | + res = requests.get('http://xkcd.com/%s' % (urlNumber)) |
| 12 | + res.raise_for_status() |
| 13 | + |
| 14 | + soup = bs4.BeautifulSoup(res.text) |
| 15 | + |
| 16 | + # Find the URL of the comic image. |
| 17 | + comicElem = soup.select('#comic img') |
| 18 | + if comicElem == []: |
| 19 | + print('Could not find comic image.') |
| 20 | + else: |
| 21 | + comicUrl = comicElem[0].get('src') |
| 22 | + # Download the image. |
| 23 | + print('Downloading image %s...' % (comicUrl)) |
| 24 | + res = requests.get(comicUrl) |
| 25 | + res.raise_for_status() |
| 26 | + |
| 27 | + # Save the image to ./xkcd |
| 28 | + imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb') |
| 29 | + for chunk in res.iter_content(100000): |
| 30 | + imageFile.write(chunk) |
| 31 | + imageFile.close() |
| 32 | + |
| 33 | +# Create and start the Thread objects. |
| 34 | +downloadThreads = [] # a list of all the Thread objects |
| 35 | +for i in range(0, 1400, 100): # loops 14 times, creates 14 threads |
| 36 | + downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99)) |
| 37 | + downloadThreads.append(downloadThread) |
| 38 | + downloadThread.start() |
| 39 | + |
| 40 | +# Wait for all threads to end. |
| 41 | +for downloadThread in downloadThreads: |
| 42 | + downloadThread.join() |
| 43 | +print('Done.') |
0 commit comments