python并发模块之concurrent.futures(二)

上次我们简单的了解下,模块的一些基本方法和用法,这里我们进一步对concurrent.futures做一个了解和拓展.
上次的内容点这。
python并发模块之concurrent.futures(二)
以下载图片为例子,下面的程序是顺序下载http://www.58pic.com/newpic/28660111.html网站的24个表情 。

from requests_html import HTMLSession
import os
import time
BASE_PATH="downloads"
class Get_Image():
    def __init__(self):
        self.timeout=20
        self.session=HTMLSession()
    def getiamge(self,url):
        req=self.session.get(url,timeout=self.timeout)
        if req.status_code==200:
            imgurllist=req.html.xpath("//ul[@class='emoticon-model']/li/img/@data-big")
            for index,url in enumerate(imgurllist):
                print(f"开始下载第{index+1}张图片")
                self.save_image(url,index+1)
        else:
            print("下载失败")
    def save_image(self,imgurl,index):
        print(f"当前下载链接:{imgurl}")
        buff=self.session.get(imgurl,timeout=self.timeout).content
        file_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),BASE_PATH)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        with open(os.path.join(file_path,f"{index}.png"),"wb") as fs:
            fs.write(buff)
if __name__ == '__main__':
    start_url="http://www.58pic.com/newpic/28660111.html"
    start=time.time()
    Get_Image().getiamge(start_url)
    end=time.time()
    print(f"顺序下载24张图片用时:{end-start}")
#运行了两次结果分别为
#顺序下载24张图片用时:14.926000356674194
#顺序下载24张图片用时:14.07800030708313

使用concurrent.futures修改成并发之后

from requests_html import HTMLSession
import os
import time
from concurrent.futures import ThreadPoolExecutor
BASE_PATH="downloads"
MAX_WORKERS = 10 #最多使用10个线程
class Get_Image():
    def __init__(self):
        self.timeout=20
        self.session=HTMLSession()
    def getiamge(self,url):
        req=self.session.get(url,timeout=self.timeout)
        if req.status_code==200:
            imgurllist=req.html.xpath("//ul[@class='emoticon-model']/li/img/@data-big")
            works=min(len(imgurllist),MAX_WORKERS)
            with ThreadPoolExecutor(works) as excutor:
                res=excutor.map(self.save_image,imgurllist,range(1,25))
            return len(list(res))
        else:
            print("下载失败")
    def save_image(self,imgurl,index):
        print(f"当前下载链接:{imgurl}")
        buff=self.session.get(imgurl,timeout=self.timeout).content
        file_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),BASE_PATH)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        with open(os.path.join(file_path,f"{index}.png"),"wb") as fs:
            fs.write(buff)
if __name__ == '__main__':
    start_url="http://www.58pic.com/newpic/28660111.html"
    start=time.time()
    Get_Image().getiamge(start_url)
    end=time.time()
    print(f"并发下载24张图片用时:{end-start}")
#运行了两次结果分别为
#并发下载24张图片用时:7.737000226974487
#并发下载24张图片用时:7.083999872207642

通过观察发现速度并发之后效率大大提高了。

python并发模块之concurrent.futures(二)的更多相关文章

  1. python并发模块之concurrent.futures(一)

    Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threadin ...

  2. python3 线程池-threadpool模块与concurrent.futures模块

    多种方法实现 python 线程池 一. 既然多线程可以缩短程序运行时间,那么,是不是线程数量越多越好呢? 显然,并不是,每一个线程的从生成到消亡也是需要时间和资源的,太多的线程会占用过多的系统资源( ...

  3. python并发编程之multiprocessing进程(二)

    python的multiprocessing模块是用来创建多进程的,下面对multiprocessing总结一下使用记录. 系列文章 python并发编程之threading线程(一) python并 ...

  4. Python3【模块】concurrent.futures模块,线程池进程池

    Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要 ...

  5. python基础-------模块与包(二)

    sys模块.logging模块.序列化 一.sys模块 sys.argv           命令行参数List,第一个元素是程序本身路径 sys.exit(n)        退出程序,正常退出时e ...

  6. Python命令模块argparse学习笔记(二)

    argparse模块可以设置两种命令参数,一个是位置参数,一个是命令参数 位置参数 import argparse parser = argparse.ArgumentParser(descripti ...

  7. Python日志模块的管理(二)

    日志模块可以通过封装一个类,也可以通过配置文件取管理 新建1个log.ini文件 [loggers] keys=root [handlers] keys=fileHandler,streamHandl ...

  8. Python学习-4.Python的模块加载(二)

    1.部分函数加载 from SameFolder import printSameFolder printSameFolder() 该代码指从SameFolder.py中加载printSameFold ...

  9. Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures

    参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...

随机推荐

  1. matlab imwrite

    函数功能:将图像数据写入到图像文件中,存储在磁盘上. 调用格式:imwrite(A,filename,fmt) A是图像数据,filename是目标图像名字,fmt是要生成的图片的格式. 图片格式有: ...

  2. hdu 2768 Cat vs. Dog (二分匹配)

    Cat vs. Dog Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  3. Selector 模型

    1.服务器端: import selectors import socket sel = selectors.DefaultSelector() #生成一个select对象 def accept(so ...

  4. CF#312 558e A Simple Task

    ~~~题面~~~ 题解: 观察到字母只有26个,因此考虑对这26个字母分别维护,每个线段树维护一个字母,如果一个线段树的某个叶节点有值,表示当前叶节点所在位置的字母是现在这个线段树代表的字母. 那么对 ...

  5. JUC包中的分而治之策略-为提高性能而生

    一.前言 本次分享我们来共同探讨JUC包中一些有意思的类,包含AtomicLong & LongAdder,ThreadLocalRandom原理. 二.AtomicLong & Lo ...

  6. HDU3652:B-number——题解

    http://acm.hdu.edu.cn/showproblem.php?pid=3652 题目大意:给一个数n,求1-n所有满足下列条件的数的个数: 1.包含一个子串为“13” 2.能被13整除. ...

  7. LOJ6354 & 洛谷4366:[Code+#4]最短路——题解

    https://loj.ac/problem/6354 https://www.luogu.org/problemnew/show/P4366 题面见上面. 这题很妙,且可能是我傻,感觉这题不太好想. ...

  8. 洛谷3805:【模板】manacher算法——题解

    https://www.luogu.org/problemnew/show/P3805 给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度. 字符串长度为n 板子题, ...

  9. kafka-zk-安装测试初体验

    第一步: 安装 安装工具brew install kafka 会自动安装依赖zookeeper 注:安装配置文件位置 /usr/local/etc/kafka|zookeeper 注: #tickTi ...

  10. bzoj3694: 最短路(树链剖分/并查集)

    bzoj1576的帮我们跑好最短路版本23333(双倍经验!嘿嘿嘿 这题可以用树链剖分或并查集写.树链剖分非常显然,并查集的写法比较妙,涨了个姿势,原来并查集的路径压缩还能这么用... 首先对于不在最 ...