Skip to content

Commit 43f5ee0

Browse files
committed
thread使用-多线程下载
1 parent 3e068ce commit 43f5ee0

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
code03 多线程下载
3+
"""
4+
import requests, os, bs4, threading
5+
6+
7+
def downlaodXkcd(startComic, endComic):
8+
for urlNumber in range(startComic, endComic):
9+
# Downlaod 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+
soup = bs4.BeautifulSoup(res.text)
14+
comicElem = soup.select('#comic img')
15+
if comicElem == []:
16+
print('Could not find comic image.')
17+
else:
18+
comicUrl = comicElem[0].get('src')
19+
# Download the image
20+
print('Downloading image %s...' % comicUrl)
21+
res = requests.get(comicUrl)
22+
res.raise_for_status()
23+
24+
# Save the image to ./xkcd
25+
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
26+
for chunk in res.iter_content(1000000):
27+
imageFile.write(chunk)
28+
29+
30+
if __name__ == '__main__':
31+
os.makedirs('xkcd', exist_ok=True)
32+
# Create and start the Thread objects
33+
downloadThreads = []
34+
for i in range(0, 1400, 100):
35+
downloadThread = threading.Thread(target=downlaodXkcd, args=(i, i + 99))
36+
downloadThreads.append(downloadThread)
37+
downloadThread.start()
38+
39+
# Wait for all threads to end
40+
for downloadThread in downloadThreads:
41+
downloadThread.join()
42+
43+
print('Done.')

0 commit comments

Comments
 (0)