pyhton如何批量保存图片
时间: 2024-06-10 21:05:50 浏览: 104
您好,以下是使用Python批量保存图片的示例代码:
```python
import requests
from urllib.parse import urlparse
def save_image(url, save_path):
response = requests.get(url)
with open(save_path, "wb") as f:
f.write(response.content)
def batch_save_images(urls, image_folder):
for url in urls:
image_name = urlparse(url).path.split("/")[-1]
save_path = f"{image_folder}/{image_name}"
save_image(url, save_path)
if __name__ == "__main__":
image_urls = ["https://example.com/image1.jpg", "https://example.com/image2.jpg"]
image_folder = "./images"
batch_save_images(image_urls, image_folder)
```
在上述代码中,我们使用了`requests`库来获取图片文件,并使用`open`函数以二进制格式写入文件。`batch_save_images`函数可接受图片URL列表和保存的文件夹路径,循环将每个URL中的图片保存到指定文件夹中。图片文件名来自URL中的路径部分。
阅读全文