json文件批量下载图片python脚本
时间: 2024-03-21 22:35:33 浏览: 15
当然,我可以为您介绍一下如何使用Python脚本批量下载图片并保存到JSON文件中。
首先,您需要安装`requests`和`json`库。您可以使用以下命令来安装它们:
```
pip install requests
```
接下来,您可以使用以下代码示例来实现批量下载图片并保存到JSON文件中:
```python
import requests
import json
def download_images(image_urls, output_folder):
image_data = []
for url in image_urls:
response = requests.get(url)
if response.status_code == 200:
image_name = url.split("/")[-1]
image_path = output_folder + "/" + image_name
with open(image_path, "wb") as f:
f.write(response.content)
image_data.append({"url": url, "path": image_path})
return image_data
def save_to_json(image_data, output_file):
with open(output_file, "w") as f:
json.dump(image_data, f, indent=4)
# 示例用法
image_urls = [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg",
"https://example.com/image3.jpg"
]
output_folder = "images"
output_file = "image_data.json"
downloaded_images = download_images(image_urls, output_folder)
save_to_json(downloaded_images, output_file)
```
在上面的示例中,`image_urls`是一个包含要下载的图片URL的列表。`output_folder`是保存下载图片的文件夹路径。`output_file`是保存图片信息的JSON文件路径。
`download_images`函数会遍历`image_urls`列表,使用`requests`库下载每个图片,并将其保存到`output_folder`文件夹中。同时,它会将每个图片的URL和保存路径添加到`image_data`列表中。
`save_to_json`函数会将`image_data`列表保存到`output_file`中,以JSON格式进行存储。
请注意,您需要根据实际情况修改示例代码中的图片URL、输出文件夹和输出文件路径。
希望这个示例能够帮助到您!如果您有任何进一步的问题,请随时提问。