注意点:
1.必须导入相关模块urllib.request ; gevent ; from gevent import monkey等模块
2.使用比较快速的连接服务器的模块urllib.request
3.准备多张图片的地址,并使用gevent模块(协程)的spawn来下载,
import urllib.request
import geventfrom gevent import monkey
monkey.patch_all()
def download(url,file_name):
'''同时下载多张图片'''
#链接服务器
res = urllib.request.urlopen(url)
#读取文件内容
content = res.read()
#保存到本地文件
with open(file_name,'wb') as file:
file.write(content)
def main():
'''测试同时下载多张图片'''
'''开启协程下载图片'''
url = [
'http://scimg.158pic.com/allimg/170601/106-1F601145Q2638.jpg',
'http://scimg.158pic.com/allimg/171020/106-1G020105133926.jpg',
'http://scimg.158pic.com/allimg/171009/106-1G009103326119.jpg'
]
g1 = gevent.spawn(download,url[0],'0.jpg')
g2 = gevent.spawn(download,url[1],'1.jpg')
g3 = gevent.spawn(download,url[2],'2.jpg')
gevent.joinall([g1,g2,g3])
# download(url[0],'0.jpg')
# download(url[1],'1.jpg')
# download(url[2],'2.jpg')
if __name__ == '__main__':
main()
备注:图片内容丰富,读者可自行下载,哈哈哈...