📅  最后修改于: 2023-12-03 15:35:31.749000             🧑  作者: Mango
Unsplash是一个网络图片平台,提供了大量优秀的高清图片供用户下载。这篇文章主要介绍在 Python 中使用 Unsplash API 来获取图片的方法和源代码。
步骤如下:
注册 Unsplash API
Unsplash API 注册地址:https://unsplash.com/developers
创建新的应用
创建新的应用,获取 Access Key 和 Secret Key。
安装 unsplash
库
pip install unsplash
导入库和设置配置项
from unsplash.api import Api
from unsplash.auth import Auth
access_key = 'Access Key'
secret_key = 'Secret Key'
auth = Auth(access_key, secret_key)
api = Api(auth)
使用 API
例如,获取随机的10张图片,并下载到本地:
import requests
import shutil
photos = api.photo.random(count=10)
for photo in photos:
response = requests.get(photo.urls.raw)
with open(f'{photo.id}.jpg', 'wb') as file:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, file)
from unsplash.api import Api
from unsplash.auth import Auth
import requests
import shutil
access_key = 'Access Key'
secret_key = 'Secret Key'
auth = Auth(access_key, secret_key)
api = Api(auth)
photos = api.photo.random(count=10)
for photo in photos:
response = requests.get(photo.urls.raw)
with open(f'{photo.id}.jpg', 'wb') as file:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, file)
该示例代码仅是 Unsplash API 的其中一种用法,读者可以根据实际需求进行修改和拓展。
更多信息,请参考 Unsplash API documentation。