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. 运行jar

    将Spring Boot 应用打包成jar, java -jar **.jar运行, 如果需要设置运行参数 java -jar **.jar --server.port=9080

  2. MD5 十六进制加密

    MD5的加密方法很多,今天说下MD5的十六进制加密···先贴方法···· class Program { static void Main(string[] args) { //202cb962ac5 ...

  3. CF546E Soldier and Traveling

    题目描述 In the country there are n n n cities and m m m bidirectional roads between them. Each city has ...

  4. 简单谈谈Docker镜像的使用方法_docker

    在上篇文章(在Docker中搭建Nginx服务器)中,我们已经介绍了如何快速地搭建一个实用的Nginx服务器.这次我们将围绕Docker镜像(Docker Image),介绍其使用方法.包括三部分: ...

  5. Python type()函数用途及使用方法

    函数可以做什么 在介绍数据类型的文章中提到过,要怎么样查看对像的数据类型.type()就是一个最实用又简单的查看数据类型的方法.type()是一个内建的函数,调用它就能够得到一个反回值,从而知道想要查 ...

  6. 【BZOJ4066】简单题(KD-Tree)

    [BZOJ4066]简单题(KD-Tree) 题面 BZOJ 题解 如果这题不卡空间,并且不强制在线的话 显然可以用\(CDQ\)分治做 但是它又卡空间又强制在线,于是我们欢快的来用\(KD-Tree ...

  7. apache的作用和tomcat的区别

    经常在用apache和tomcat等这些服务器,可是总感觉还是不清楚他们之间有什么关系,在用tomcat的时候总出现apache,总感到迷惑,到底谁是主谁是次,因此特意在网上查询了一些这方面的资料,总 ...

  8. nginx 静态服务器设置

    一.配置Nginx [root@VM_16_15_centos nginx]# cd conf.d/ [root@VM_16_15_centos conf.d]# ll total 4 -rwxr-x ...

  9. php防止用户输入进行跨站攻击的方式

    1.对用户输入的内容进行转义 //1.过滤内容中html标记 $userinput=strip_tags($userinput); //2.转换成HTML实体 $userinput=htmlentit ...

  10. 数据结构:K-D树

    K-D树实际上是一棵高维二叉搜索树,与普通二叉搜索树不同的是,树中存储的是一些K维数据 普通的二叉搜索树是一维的,当推广到K维后,就是我们的K-D树了 在K-D树中跟二叉搜索树差不多,也是将一个K维的 ...