以下是一个示例代码,用于按照相同顺序从链接列表中下载图像:
import requests
import os
def download_image(url, file_name):
response = requests.get(url)
with open(file_name, 'wb') as file:
file.write(response.content)
def download_images(link_list, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for index, link in enumerate(link_list):
file_name = os.path.join(output_dir, f"image{index}.jpg")
download_image(link, file_name)
print(f"Downloaded image {index+1}/{len(link_list)}")
# 示例链接列表
link_list = [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg",
"https://example.com/image3.jpg"
]
# 指定输出目录
output_dir = "images"
# 调用下载函数
download_images(link_list, output_dir)
在上面的示例代码中,download_image
函数用于下载单个图像文件,它接受一个URL和文件名作为参数,并使用requests
库发送GET请求来获取图像的二进制数据,并将其写入到指定的文件中。
download_images
函数用于遍历链接列表,并调用download_image
函数来下载每个链接对应的图像文件。它还会创建输出目录(如果不存在的话),并使用os.makedirs
函数来确保目录的存在。
在示例中,我们使用了一个简单的命名约定来命名下载的图像文件,即image0.jpg、image1.jpg等。你可以根据自己的需求修改这个命名约定。
最后,我们提供了一个示例链接列表和一个输出目录,并调用download_images
函数来开始下载图像。下载过程中,会打印出每个图像的下载进度。
请注意,上述示例仅为演示目的,并未考虑异常处理、并发下载等情况。在实际应用中,你可能需要添加适当的错误处理和优化措施。
下一篇:按照相同属性进行数组过滤并连接