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. CentOS LVM逻辑卷管理

    在CentOS 挂载(U盘NTFS格式,新硬盘,增加交换分区,扩展根分区等)中扩展根分区部分用的就是LVM逻辑卷管理来进行扩展的. 1.为什么会有逻辑卷管理 传统磁盘管理是直接对硬盘分区进行访问,你如 ...

  2. UVA.357 Let Me Count The Ways (DP 完全背包)

    UVA.357 Let Me Count The Ways (DP 完全背包) 题意分析 与UVA.UVA.674 Coin Change是一模一样的题.需要注意的是,此题的数据量较大,dp数组需要使 ...

  3. 删边(cip)

    删边(cip) 给出一个没有重边和自环的无向图,现在要求删除其中两条边,使得图仍然保持连通. 你的任务是计算有多少组不合法的选边方案.注意方案是无序二元组. Sol 神题,无从下手啊. 考虑点dfs建 ...

  4. [BZOJ1106/POI2007]Tet立方体大作战

    Description 一个叫做立方体大作战的游戏风靡整个Byteotia.这个游戏的规则是相当复杂的,所以我们只介绍他的简单规则:给定玩家一个有2n个元素的栈,元素一个叠一个地放置.这些元素拥有n个 ...

  5. angularJS 条件查询 品优购条件查询品牌(条件查询和列表展示公用方法解决思路 及 post请求混合参数提交方式)

    Brand.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> &l ...

  6. mybaties分页

    首先引入jar包: <dependency> <groupId>com.github.pagehelper</groupId> <artifactId> ...

  7. UVA10766:Organising the Organisation(生成树计数)

    Organising the Organisation 题目链接:https://vjudge.net/problem/UVA-10766 Description: I am the chief of ...

  8. HTML学习基本代码

    HTML的代码比较繁琐,在此记下一些基本的东西,以后自己回来看看 <html> <head> <title>我的人生啊</title> <styl ...

  9. crontab 定期拉取代码

    * * * * * cd /home/wwwroot/default/lion/ && /usr/bin/git pull origin 5hao >> /tmp/git. ...

  10. java 面向对象编程(OOP)

    java是一个支持并发.基于类和面向对象的计算机编程语言.下面列出了面向对象软件开发的优点: 代码开发模块化,更易维护和修改: 代码复用: 增加代码的可靠性和灵活性: 增加代码的可理解性. 封装 封装 ...