Image 从大都会博物馆收藏中下载的图像为空
我正试图使用大都会博物馆收藏的API(更多信息,请参见此处)和Python从大都会博物馆随机下载公共域图像,不幸的是,我得到的图像是空的。下面是一个最低限度的代码:Image 从大都会博物馆收藏中下载的图像为空,image,python-2.7,api,download,urlrequest,Image,Python 2.7,Api,Download,Urlrequest,我正试图使用大都会博物馆收藏的API(更多信息,请参见此处)和Python从大都会博物馆随机下载公共域图像,不幸的是,我得到的图像是空的。下面是一个最低限度的代码: import urllib from urllib2 import urlopen import json from random import randint url = "https://collectionapi.metmuseum.org/public/collection/v1/objects" objectID_lis
import urllib
from urllib2 import urlopen
import json
from random import randint
url = "https://collectionapi.metmuseum.org/public/collection/v1/objects"
objectID_list = json.loads(urlopen(url).read())['objectIDs']
objectID = objectID_list[randint(0,len(objectID_list)-1)]
url_request = url+"/"+str(objectID)
fetched_data = json.loads(urlopen(url_request).read())
if fetched_data['isPublicDomain']:
name = str(fetched_data['title'])
ID = str(fetched_data['objectID'])
url_image = str(fetched_data['primaryImage'])
urllib.urlretrieve(url_image, 'path/'+name+'_'+ID+'.jpg')
如果我打印url_图像并将其复制/粘贴到浏览器中,我会得到所需的图像,但代码检索到的图像重量为1ko,无法打开。
知道我做错了什么吗?您的下载方式是正确的,但是,域似乎正在验证请求头以防止刮取(可能是无意的,因为它们有一个用于拉取图像的API) 解决此问题的一种方法是将标题更改为现实的标题,或者利用和
请求
import requests
from fake_useragent import UserAgent
def save_image(link, file_path):
ua = UserAgent(verify_ssl=False)
headers = {"User-Agent": ua.random}
r = requests.get(link, stream=True, headers=headers)
if r.status_code == 200:
with open(file_path, 'wb') as f:
f.write(r.content)
else:
raise Exception("Error code {}.".format(r.status_code))
好吧,它对两幅图像有效,然后停止工作。现在图像又是1ko了。