我一直在尝试寻找方法来转换从我正在使用的 API 中收集的图像 URL,但它一直返回 403 状态代码。 URL 是有效的 jpeg 图像。它应该拍摄用户选择的相册的图像。
def getDetails():
url = f"https://api.discogs.com/masters/{albumid}?&key=hidden,secret=hidden"
response = requests.get(url)
data = response.json()
with open("Ex1.json",'w') as file:
json.dump(data,file,indent =6)
try:
image_url = data['images'][0]['uri']
x = requests.get(image_url)
print(image_url)
if x.status_code == 200:
img = Image.open(BytesIO(x))
return img
else:
print(f"Failed to fetch image {x.status_code}")
except (KeyError, IndexError) as e:
print(f"Error fetching image: {e}")
打印的内容如下: (带有示例输入)
NewJeans - Get Up
https://i.discogs.com/fh2tUe8Qtjtzt96_CQbRnLj6gpf6I45kP2Xw-UoTVMI/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTI3NzM2/NTEyLTE2ODk5MTQ3/NzItOTA0NS5qcGVn.jpeg
Failed to fetch image 403
您在标题中缺少 User-Agent,在 this 之后,我已设法使用您作为 example 提供的 url 获取此脚本,并获取您尝试下载的图像/使用
import requests as req
res = req.get("https://i.discogs.com/fh2tUe8Qtjtzt96_CQbRnLj6gpf6I45kP2Xw-UoTVMI/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTI3NzM2/NTEyLTE2ODk5MTQ3/NzItOTA0NS5qcGVn.jpeg", headers={"User-Agent":"discogs_api_example/1.0"})
# print(res.content)
with open("x.jpeg", "wb") as f:
f.write(res.content)
根据需要替换为您的代码。