【问题标题】:How do I download images using the Scryfall API and Python如何使用 Scryfall API 和 Python 下载图像
【发布时间】:2019-03-13 17:10:41
【问题描述】:

在这方面对 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

【问题讨论】:

    标签: python json api


    【解决方案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 在发出请求时遇到的任何异常。如果什么都没发生,这意味着我们收到了一个 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 的信息,请查看documentation

    【讨论】:

    • 我假设因为我想从整个 json 中获取所有“正常”图像,所以我需要构建一个循环来执行此操作并将结果保存到列表中,然后循环遍历列表并下载图片?
    • 我想我也需要将json导入Python吧?
    猜你喜欢
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2020-04-09
    • 2020-07-20
    • 1970-01-01
    相关资源
    最近更新 更多