Python3 多线程下载图片

import requests
import time
import threading
import queue

s='https://avatar.csdn.net/D/0/A/3_u013440574.jpg'
urls=[]
[urls.append(s) for i in range(100)]
q = queue.Queue()
for url in urls:
    q.put(url)
start = time.time()
def fetch_img_func(q):
    while True:
        try:
            url = q.get_nowait()# 不阻塞的读取队列数据
            i = q.qsize()
        except Exception as e:
            print (e)
            break
        # print ('Current Thread Name Runing %s ... ' % threading.currentThread().name)
        print("当前还有%s个任务"% i)
        res = requests.get(url, stream=True)
        if res.status_code == 200:
            save_img_path ='img/%s.jpg'%i
            # 保存下载的图片
            with open(save_img_path, 'wb') as fs:
                for chunk in res.iter_content(1024):
                    fs.write(chunk)

num=10  #线程数
threads =[]
for i  in range(num):
    t = threading.Thread(target=fetch_img_func, args=(q, ), name="child_thread_%s"%i)
    threads.append(t)
for t in threads:
    t.start()
for t in threads:
    t.join()

print(time.time()-start)
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值