python 多线程下载图片_python多线程下载网页图片并保存至特定目录

#!python3

#multidownloadXkcd.py - Download XKCD comics using multiple threads.

import requests

import bs4

import os

import threading

# os.mkdir('xkcd', exist_ok=True) # store comics in ./xkcd

if os.path.exists('xkcd'):

print("xkcd is existed!")

else:

os.mkdir('xkcd')

def downloadXkcd(startComic, endComic):

for urlNumber in range(startComic, endComic):

#Download the page

print("Downloading page http://xkcd.com/%s..." % urlNumber)

res = requests.get('http://xkcd.com/%s' % urlNumber)

res.raise_for_status()

print(res.text)

soup = bs4.BeautifulSoup(res.text)

#Find the URL of the comic image.

comicElem = soup.select('#comic img')

if comicElem == []:

print('Could not find comic images.')

else:

comicUrl = comicElem[0].get('src')

# #Download the image.

# print('Downloading image %s...' % (comicUrl))

# res = requests.get(comicUrl)

# res.raise_for_status()

#

# # Save the image to ./xkcd

# imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')

# for chunk in res.iter_content(100000):

# imageFile.write(chunk)

# imageFile.close()

downloadThread = threading.Thread(target=downloadXkcd(555, 557))

downloadThread.start()

# # TODO: Create and start the thread objects

# downloadThreads = [] # a list of all the Thread objects

# for i in range(500, 600, 10):

# downloadThread = threading.Thread(target=downloadXkcd, args=(i, i+9))

# downloadThreads.append(downloadThread)

# downloadThread.start()

#

# # TODO: Wait for all threads to end

# for downloadThread in downloadThreads:

# downloadThread.join()

# print("Done.")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值