Python线程池下载txt图片

导读:本篇文章讲解 Python线程池下载txt图片,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

第一个例子,从某个网站下载小说txt文档,入参i为url中的id。

# coding=utf-8
import requests
import threadpool

def download_file(i):
    '''下载文件'''
    download_url = f"https://www.txt2016.com/e/DownSys/xiazai/?classid=1&pathid=0&id={i}"
    file = requests.get(download_url)

    try:
        filename = file.headers['Content-Disposition'][21:][:-19].encode('iso8859-1').decode('utf-8') 
        filename = filename.replace('/','-') + '.txt'
        # print(filename)
        with open(f'./txt/{filename}', 'wb') as txt_file:
            txt_file.write(file.content)
        print(i, ': ', filename)
    except KeyError:
        print(file.headers)
        print(file.status_code)
        print("网址不存在")


if __name__ == "__main__":
    ids = [i for i in range(2275, 113642)]  # 把每次任务的入参准备好, 让pool自己去调度
    pool = threadpool.ThreadPool(8) # 线程池设置,最多同时跑8个线程
    tasks = threadpool.makeRequests(download_file, ids)
    # makeRequests构造线程task请求, 第一个参数是线程函数, 第二个是参数数组
    [pool.putRequest(task) for task in tasks]
    # 列表推导式, putRequest向线程池里加task, 让pool自己去调度task
    pool.wait() # 等所有任务结束

第二个例子,从excel中读取图片文件的下载地址,用线程池进行下载,因为需要重命名文件,所以还包含了线程池的多入参操作

download_img函数的入参有两个,所以先用元组组装起来(piclist[0],f”{i}_0″)

然后对于线程池threadpool.makeRequests的方法,第二个入参表示被调用任务的所有入参的枚举,而且每个枚举值的下标【0】会解析为list,下标【1】为dic,咱们用的元组,所以第二位用None占位,单个枚举值组装为((piclist[0],f”{i}_0″),None)

最后再把这些枚举值组装成urls

# coding: utf8
import requests
import threadpool
import pandas as pd


def download_img(img_url,filename):
    r = requests.get(img_url, stream=True)
    # print(r.status_code) # 返回状态码
    if r.status_code == 200:
        with open(f'./pics2/{filename}.jpg', 'wb') as f:
            f.write(r.content)   


def pic_downv2():
    df = pd.read_excel("data.xlsx", usecols="I:K").values   # 从excel读取3列数据
    urls = []

    for i in range(1,905):
        print(i)
        piclist = df[int(i)].tolist()
        urls.append(((piclist[0],f"{i}_0"),None))
        urls.append(((piclist[1],f"{i}_1"),None))
        urls.append(((piclist[2],f"{i}_2"),None))  # 组装入参

    pool = threadpool.ThreadPool(8)
    tasks = threadpool.makeRequests(download_img, urls)
    [pool.putRequest(task) for task in tasks]
    pool.wait()

pic_downv2()

代码参考:Python数据抓取——多线程,异步_Young_618-CSDN博客_python异步多线程

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/4673.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!