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)

猜你喜欢

转载自blog.csdn.net/u013440574/article/details/81907937