python 并发下载器

目标:使用协程实现网络图片下载

 思路

        1.根据url地址请求网络资源

        2.在本地创建文件准备保存

        3.读取网络资源数据

        4.把读取的网络资源写入到本地文件中

        5.做异常捕获

代码

单线程下载:

import urllib

def download_img(imgUrl, fileName):
    # 根据url请求网络资源
    response_data = urllib.request.urlopen(imgUrl)
    # 在本地创建文件,准备保存
    with open(fileName, "wb") as file:
        while True:
            # 读取网络资源
            file_data = response_data.read(1024)
            # 判断读取的数据是否为空,不为空继续写,为则表示已经读到文件末尾,需跳出循环
            if file_data:
                # 写入本地文件
                file.write(file_data)
            else:
                break

def main():
    # 要下载图片的路径
    img1Url = "https://www.qqpao.com/uploads/allimg/181116/10-1Q116102128.gif"
    img2Url = "https://uploadfile.huiyi8.com/2014/1107/20141107114402602.gif"
    img3Url = "https://media1.giphy.com/media/l41lXnhesd96Aa9os/giphy.gif"

    download_img(img1Url,"C:/Users/Desktop/1.gif")
    download_img(img2Url, "C:/Users/Desktop/2.gif")
    download_img(img3Url, "C:/Users/Desktop/3.gif")

if __name__ == '__main__':
    main()

使用协程实现并发下载:

import urllib,gevent,requests
from gevent import monkey
monkey.patch_all()

def download_img(imgUrl, fileName):
    try:
        # 根据url请求网络资源
        response_data = urllib.request.urlopen(imgUrl)
        # 在本地创建文件,准备保存
        with open(fileName, "wb") as file:
            while True:
                # 读取网络资源
                file_data = response_data.read(1024)
                # 判断读取的数据是否为空,不为空继续写,为则表示已经读到文件末尾,需跳出循环
                if file_data:
                    # 写入本地文件
                    file.write(file_data)
                else:
                    break
    except Exception as e:
        print("文件 %s 下载失败! %s" % (fileName,e))
    else:
        print("文件 %s 下载成功!" % (fileName))

def main():
    # 要下载图片的路径
    img1Url = "https://www.qqpao.com/uploads/allimg/181116/10-1Q116102128.gif"
    img2Url = "https://uploadfile.huiyi8.com/2014/1107/20141107114402602.gif"
    img3Url = "https://media1.giphy.com/media/l41lXnhesd96Aa9os/giphy.gif"

    gevent.joinall([
        gevent.spawn(download_img, img1Url, "C:/Users/Desktop/1.gif"),
        gevent.spawn(download_img, img2Url, "C:/Users/Desktop/2.gif"),
        gevent.spawn(download_img, img3Url, "C:/Users/Desktop/3.gif"),
    ])

if __name__ == '__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zhichao_97

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值