python笔记13-多线程实战篇(tomorrow)

本文介绍了一种利用Python库Tomorrow简化多线程操作的方法,通过对比单线程与多线程环境下爬取图片的效率,展示了如何仅通过一行装饰器代码实现性能的显著提升。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装

1.tomorrow安装,用pip可以直接安装

pip install tomorrow

单线程

1。以下案例是单线程时候跑的情况,在下载图片的时候很耗时。

# coding:utf-8
from bs4 import BeautifulSoup
import requests
import os
import time

# 当前脚本所在的目录
cur_path = os.path.dirname(os.path.realpath(__file__))


def get_img_urls():
    r = requests.get("http://699pic.com/sousuo-218808-13-1.html")
    fengjing = r.content
    soup = BeautifulSoup(fengjing, "html.parser")
    # 找出所有的标签
    images = soup.find_all(class_="lazy")
    return images

def save_img(imgUrl):
    try:
        jpg_rl = imgUrl["data-original"]
        title = imgUrl["title"]
        # print(title)
        # print(jpg_rl)
        # print("")
        # 判断是否有jpg文件夹,不存在创建一个
        save_file = os.path.join(cur_path, "jpg")
        if not os.path.exists(save_file): os.makedirs(save_file)

        with open(os.path.join(save_file, title+'.jpg'), "wb") as f:
            f.write(requests.get(jpg_rl).content)
    except:
        pass

if __name__ == "__main__":
    t1 = time.time()

    image_ulrs = get_img_urls()
    for i in image_ulrs:
        save_img(i)

    t2 = time.time()
    print("总耗时:%.2f 秒"%(t2-t1))

运行结果:

耗时:4.27 秒

使用多线程tomorrow

1.一行代码搞定多线程,在函数上加个@threads(5),括号里面代码线程的数量,数字越大,运行的速度越快

# coding:utf-8
from bs4 import BeautifulSoup
import requests
import os
import time
from tomorrow import threads

# 当前脚本所在的目录
cur_path = os.path.dirname(os.path.realpath(__file__))


def get_img_urls():
    r = requests.get("http://699pic.com/sousuo-218808-13-1.html")
    fengjing = r.content
    soup = BeautifulSoup(fengjing, "html.parser")
    # 找出所有的标签
    images = soup.find_all(class_="lazy")
    return images

@threads(5)
def save_img(imgUrl):
    try:
        jpg_rl = imgUrl["data-original"]
        title = imgUrl["title"]
        # print(title)
        # print(jpg_rl)
        # print("")
        # 判断是否有jpg文件夹,不存在创建一个
        save_file = os.path.join(cur_path, "jpg")
        if not os.path.exists(save_file): os.makedirs(save_file)

        with open(os.path.join(save_file, title+'.jpg'), "wb") as f:
            f.write(requests.get(jpg_rl).content)
    except:
        pass

if __name__ == "__main__":
    t1 = time.time()


    image_ulrs = get_img_urls()
    for i in image_ulrs:
        save_img(i)

    t2 = time.time()
    print("总耗时:%.2f 秒"%(t2-t1))

运行结果:

总耗时:0.24 秒

参考github案例:Tomorrow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值