繁体   English   中英

如何使用Scryfall API和Python下载图像

[英]How do I download images using the Scryfall API and Python

对于API和Python而言,这是相当新的东西。 我需要使用它们的API从Scryfall抓取图像。 这是指向API文档的链接。 https://scryfall.com/docs/api

他们正在使用json,代码看起来像这样。 https://api.scryfall.com/cards/cn2/78?format=json&pretty=true

这是包含图像URI的部分。

 "image_uris": {
    "small": "https://img.scryfall.com/cards/small/en/cn2/78.jpg?1517813031",
    "normal": "https://img.scryfall.com/cards/normal/en/cn2/78.jpg?1517813031",
    "large": "https://img.scryfall.com/cards/large/en/cn2/78.jpg?1517813031",
    "png": "https://img.scryfall.com/cards/png/en/cn2/78.png?1517813031",
    "art_crop": "https://img.scryfall.com/cards/art_crop/en/cn2/78.jpg?1517813031",
    "border_crop": "https://img.scryfall.com/cards/border_crop/en/cn2/78.jpg?1517813031"
  },

我将如何在这些URI处获取图像并下载它们?

我在github上找到了这个,但是我不确定从哪里开始。 https://github.com/NandaScott/Scrython

我正在使用此页面上的“默认卡”文件https://scryfall.com/docs/api/bulk-data

您需要下载图像数据并将其保存在本地。 步骤1,使用Python获取图像数据:

import requests as req

img_uris = {
    "small": "https://img.scryfall.com/cards/small/en/cn2/78.jpg?1517813031",
    "normal": "https://img.scryfall.com/cards/normal/en/cn2/78.jpg?1517813031",
    "large": "https://img.scryfall.com/cards/large/en/cn2/78.jpg?1517813031",
    "png": "https://img.scryfall.com/cards/png/en/cn2/78.png?1517813031",
    "art_crop": "https://img.scryfall.com/cards/art_crop/en/cn2/78.jpg?1517813031",
    "border_crop": "https://img.scryfall.com/cards/border_crop/en/cn2/78.jpg?1517813031"
}

img_request = req.get(img_uris['normal'])
# Always test your response obj before performing any work!
img_request.raise_for_status()

函数raise_for_status()将在发出requests时引发任何异常requests 如果什么都没发生,则意味着我们收到了200个响应代码,表明我们的要求很好! 现在执行步骤2,保存数据:

import os
img_file = "queen_marchesa_norm.jpg"

with open(os.path.join(os.getcwd(), img_file), 'w') as f:
    f.write(img_request.content)

在这里,我们声明一个文件名,使用该文件名创建一个可写的文件对象,然后将所有数据从img_request写入我们的文件对象。 如果您想了解有关requests更多信息, requests查阅文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM