如何使用特定名称保存下载的图像?

How to save downloaded images with a specific name?

我有这段代码循环遍历 df(excel 文件)并为要保存的图像创建 link。 该代码可用于为图像创建 links,但我无法使用在我的 df

中找到的 links 名称保存图像

例如:

/images/S/aplus-media/vc/9c4fd284-2d51-47d8-8275-9977cc5f9771.jpg
lst = just_img_col.values.tolist()

var = 'https://m.media-amazon.com/'

for val in lst:
    for ele in val:
      if len(str(ele)) > 10:
        image_url = var + str(ele)
        print(image_url)
        r = requests.get(image_url, stream=True)
        filename = str(ele)
        print(filename)

 if r.status_code == 200:
    r.raw.decode_content = True

# Open a local file with wb ( write binary ) permission.
with open(filename, 'wb') as f:
    shutil.copyfileobj(r.raw, f)

print('Image sucessfully Downloaded: ', filename)
else:
   print('Image Couldn\'t be retreived')

有什么我应该添加到我的代码中,以便我可以用这种格式的名称保存图像: /images/S/aplus-media/vc/9c4fd284-2d51-47d8-8275-9977cc5f9771.jpg?

links 的一些示例:

https://m.media-amazon.com//images/S/aplus-media/vc/aa7c7a6e-6ad8-4f14-997a-49b379fae2b4.jpg
https://m.media-amazon.com//images/S/aplus-media/vc/9eff75e4-c9b2-4fc6-8f88-5a8ac57d5aca.jpg
https://m.media-amazon.com//images/S/aplus-media/sota/bb556924-6691-4510-82aa-e13360fb5acf.jpg
https://m.media-amazon.com//images/S/aplus-media/vc/2e87df92-06e3-4fc2-9781-86f0e50ac867.jpg
https://m.media-amazon.com//images/S/aplus-media/vc/6bcafb85-8836-43ef-9d18-da3ce64b4e0b.jpg

确保 varele 具有以下结构。看来你在搞乱正斜杠 /。在 GET 请求之前尝试 printing image_url

import os
import requests


var = 'https://m.media-amazon.com/'
lst = [['/images/S/aplus-media/vc/9c4fd284-2d51-47d8-8275-9977cc5f9771.jpg']]

for val in lst:
    for ele in val:
        if len(str(ele)) > 10:
            image_url = os.path.join(var[:-1], str(ele)[1:])
            print(image_url)
            r = requests.get(image_url)
            filename = str(ele).replace('/', '_')
            

            if r.status_code == 200:
                # r.raw.decode_content = True
                # Open a local file with wb ( write binary ) permission.
                with open(filename, 'wb') as f:
                    f.write(r.content)

                print('Image sucessfully Downloaded: ', filename)
            else:
                print('Image Couldn\'t be retreived')