当前位置:实例文章 » 其他实例» [文章]python 批量下载图片(协程)

python 批量下载图片(协程)

发布人:shili8 发布时间:2025-02-06 23:25 阅读次数:0

**批量下载图片使用Python协程**

在这个教程中,我们将使用Python的协程功能来实现批量下载图片。我们将使用`requests`库来发送HTTP请求,`concurrent.futures`库来管理协程。

### 安装所需库首先,我们需要安装所需的库。如果你已经安装了它们,可以跳过这一步:

bashpip install requests concurrent.futures


### 准备工作我们需要准备一个列表来存储图片的URL。假设我们有一个名为`image_urls.txt`的文件,里面包含了图片的URL:

# image_urls.txt />


### 定义协程函数下面是定义协程函数的代码:

import osfrom concurrent.futures import ThreadPoolExecutorimport requestsdef download_image(url, image_dir):
 """
 下载图片并保存到指定目录 Args:
 url (str): 图片URL image_dir (str):保存图片的目录 """
 # 检查目录是否存在,不存在则创建 if not os.path.exists(image_dir):
 os.makedirs(image_dir)
 # 下载图片并保存到指定目录 response = requests.get(url, stream=True)
 if response.status_code ==200:
 with open(os.path.join(image_dir, url.split("/")[-1]), "wb") as f:
 for chunk in response.iter_content(chunk_size=1024):
 f.write(chunk)

def main():
 #读取图片URL列表 with open("image_urls.txt", "r") as f:
 image_urls = [line.strip() for line in f.readlines()]
 # 指定保存图片的目录 image_dir = "images"
 # 创建线程池 with ThreadPoolExecutor(max_workers=5) as executor:
 # 执行下载任务 futures = {executor.submit(download_image, url, image_dir): url for url in image_urls}
 # 等待所有任务完成 for future in futures:
 future.result()

if __name__ == "__main__":
 main()


###代码注释* `download_image`函数负责下载图片并保存到指定目录。
* `main`函数读取图片URL列表,指定保存图片的目录,并创建线程池。
* 使用`ThreadPoolExecutor`来管理协程,最大工作线程数为5。
* 执行下载任务后,使用`futures`字典来等待所有任务完成。

### 总结在这个教程中,我们使用Python的协程功能实现了批量下载图片。我们使用`requests`库发送HTTP请求,`concurrent.futures`库管理协程。通过定义一个协程函数和主函数,我们可以轻松地下载大量图片并保存到指定目录。

### 扩展阅读* [Python协程教程]( />* [requests库文档]( />* [concurrent.futures库文档](

相关标签:python开发语言
其他信息

其他资源

Top