python 根据地址列表6线程下载图片到同一文件夹中
时间: 2024-06-09 14:08:29 浏览: 9
下面是一个使用 Python 多线程下载图片的示例代码:
```python
import requests
import threading
import os
def download_image(url, filename):
response = requests.get(url)
with open(filename, 'wb') as f:
f.write(response.content)
def download_images(urls, folder):
if not os.path.exists(folder):
os.makedirs(folder)
threads = []
for i, url in enumerate(urls):
filename = os.path.join(folder, f'image_{i}.jpg')
thread = threading.Thread(target=download_image, args=(url, filename))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
if __name__ == '__main__':
urls = [
'http://example.com/image1.jpg',
'http://example.com/image2.jpg',
'http://example.com/image3.jpg',
'http://example.com/image4.jpg',
'http://example.com/image5.jpg',
'http://example.com/image6.jpg',
]
folder = 'images'
download_images(urls, folder)
```
这个示例代码中,我们定义了一个 `download_image` 函数来下载单个图片,然后定义了一个 `download_images` 函数来下载多个图片。`download_images` 函数使用一个线程列表来存储每个下载任务的线程,并且在启动每个线程之后,使用 `join` 方法来等待所有线程完成下载任务。在下载图片之前,我们还检查了文件夹是否存在,如果不存在则创建该文件夹。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)