应用程序编程接口 (API) 是一组用于访问 Web 应用程序的指令。今天,我们将使用 Python 和 NASA 的 Open API 创建一个获取每日天文图像的程序。

这篇文章是由 Pratik Shukla 作为他的天文游戏系列的一部分写的。


谁不喜欢那些迷人的太空图像!

美国国家航空航天局 (NASA) 通过“每日天文图片”服务提供令人惊叹的天文图像。在本教程中,我们将使用 NASA API 和 nasa.py 库来获取这些图像。

应用程序编程接口 (API) 是一组用于访问 Web 应用程序的指令和标准。 API 是一个非常有用的工具,它允许我们公开共享信息。学习如何使用 API 的最佳方式是自己编程。

今天,我们将学习如何下载和显示每日天文图像。首先,我们要取今天的。图片。然后,我们将对代码进行一些更改,以便我们自动获取任何日期的图像。

这是我们今天要介绍的内容:

  • 使用 NASA 的 API 获取当天的天文图片

  • 根据日期值获取天文图像

  • 下载一系列日期的天文图像

  • 结束

使用 NASA 的 API 获取当天的天文学图片

在下面的程序中。我们将使用 NASA 的开放 API 下载今天的天文图片(APOD)。该程序将仅下载图像文件。如果今天没有可用的图像文件,它只会打印一条消息,上面写着“图像不可用”。

如果图像文件可用,它将被下载到本地系统。然后,我们的代码将从本地系统获取图像并将其与任何额外信息(即标题、url)一起显示。

接下来,我们的代码将询问用户是否想听到图像的音频解释。如果用户选择收听音频解释,我们将使用 Google 文本转语音 (GTTS) 库将文本解释转换为音频文件并播放。

注意: 要访问 NASA 提供的服务,我们需要有一个注册的 api 密钥。要获得 api 密钥,我们只需在 NASA API 网站上填写](https://api.nasa.gov/)表格[。我们也可以使用demo_key

我们通过注册的api每小时可以发出1000个请求,而demo_key我们每天只能发出50个请求。

注册成功后,您将在提到的电子邮件地址中获得一个 api 密钥。我们将在本教程后面使用此密钥。

[Alt](https://res.cloudinary.com/practicaldev/image/fetch/s--i-t0umIE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https:// dev-to-uploads.s3.amazonaws.com/i/koso3yprc2b2l4np1vwl.png)

Python实现(5步)

第一步:导入需要的库

#Import required libraries:
import nasapy
import os
from datetime import datetime
import urllib.request
from IPython.display import Image,display,Audio
from gtts import gTTS

进入全屏模式 退出全屏模式

  • nasapy:我们将使用 nasapy 库来访问 NASA 的 API 提供的信息。

  • os:要将图像存储在特定目录中,我们使用 os 库。

  • datetime:我们在向 NASA API 发送请求以访问信息时使用日期。要获取特定格式的日期,我们将使用日期时间库。

  • urllib:我们从 NASA API 获取的图像将是 URL 的形式,因此我们使用 urllib 来获取它。

  • Ipython:我们需要使用 Ipython 库在 jupyter notebook 中显示图像。我们还将使用音频模块播放图像的音频解释。

  • gtts:我们使用 Google Text to Speech 库将图像的文字说明转换为音频文件。

Step 2. 创建 Nasa 类的对象

在这里,我们将创建一个名为nasa的对象。我们正在使用nasapy库和我们注册的 api 密钥。我们将使用该对象调用Nasa类的方法来获取有关天文图像的信息。

#Initialize Nasa class by creating an object:

k = "523p5hPYHGzafYGLCkqa54kKMTV2vbP0XcPxkcLm"
nasa = nasapy.Nasa(key = k)

进入全屏模式 退出全屏模式

Step 3. 获取所需格式的日期

现在要获取特定日期的图像,我们需要以特定格式传递日期。使用datetime.today()函数所需的日期格式为YYYY-MM-DD。因此,我们需要使用strftime(%Y-%m-%d)函数将此元组转换为字符串。

#Get today's date in YYYY-MM-DD format:

d = datetime.today().strftime('%Y-%m-%d')

进入全屏模式 退出全屏模式

步骤 4. 从 NASA 的 API 获取信息

现在我们有了正确格式的今天日期,我们可以请求今天的天文图像。这里我们使用picture_of_the_day()方法来获取图像数据。

#Get the image data:

apod = nasa.picture_of_the_day(date=d, hd=True)

进入全屏模式 退出全屏模式

我们的 apod 变量是一个包含各种键和值的字典。让我们看一下这个变量的键:

  • date

  • title

  • copyright

  • explanation

  • url

  • hdurl

  • media_type

  • service_version

Step 5. 显示图像等信息

#POINT A:
#Check the media type available:
if(apod["media_type"] == "image"):

    #POINT B:
    #Displaying hd images only:
    if("hdurl" in apod.keys()):

        #POINT C:
        #Saving name for image:
        title = d + "_" + apod["title"].replace(" ","_").replace(":","_") + ".jpg"

        #POINT D:
        #Path of the directory:
        image_dir = "./Astro_Images"

        #Checking if the directory already exists?
        dir_res = os.path.exists(image_dir)

        #If it doesn't exist then make a new directory:
        if (dir_res==False):
            os.makedirs(image_dir)

        #If it exist then print a statement:
        else:
            print("Directory already exists!\n")

        #POINT E:
        #Retrieving the image:
        urllib.request.urlretrieve(url = apod["hdurl"] , filename = os.path.join(image_dir,title))

        #POINT F:
        #Displaying information related to image:

        if("date" in apod.keys()):
            print("Date image released: ",apod["date"])
            print("\n")
        if("copyright" in apod.keys()):
            print("This image is owned by: ",apod["copyright"])
            print("\n")
        if("title" in apod.keys()):
            print("Title of the image: ",apod["title"])
            print("\n")
        if("explanation" in apod.keys()):
            print("Description for the image: ",apod["explanation"])
            print("\n")
        if("hdurl" in apod.keys()):
            print("URL for this image: ",apod["hdurl"])
            print("\n")

        #POINT G:
        #Displaying main image:
        display(Image(os.path.join(image_dir,title)))

        #Point H:
        #Text to Speech Conversion:
        #Take input from user:
        print("\n")
        choice = input("Press * to hear the audio explanation : ")

        if(choice=="*"):
            #Text to be converted:
            mytext = apod["explanation"]
            #mytext="Good Evening Pratik."

            #Creating an object:
            myobj = gTTS(text=mytext, lang="en", slow=False) 

            #Generating audio file name:
            audio_title = d + "_" + apod["title"] + ".mp3"

            #Save the converted file:
            myobj.save(os.path.join(image_dir,audio_title)) 

            #Name of sound file:
            sound_file = os.path.join(image_dir,audio_title)

            # Playing the converted file 
            display(Audio(sound_file, autoplay=True))



#POINT I:
#If media type is not image:
else:
    print("Sorry, Image not available!")

进入全屏模式 退出全屏模式

现在我们将逐块理解代码。

显示图像:

  • 首先,我们只显示图像。

  • 接下来,我们只对高清图像感兴趣。因此,如果我们的图像具有标准清晰度,那么我们就不会进入循环。

  • 现在,我们必须保持某种名称结构来保存图像。在这里,我们将使用图像的日期,然后是图像的标题,然后是图像的扩展名。

  • 我们还将冒号和空格替换为下划线。

创建目录:

  • 现在我们必须有一个特定的目录来存储图像。我们使用 os 库创建一个目录。要检查目录是否存在,我们使用.exist()函数。如果目录不存在,那么我们使用.makedirs()函数创建它。

  • 现在我们使用在 apod 变量中检索到的 url 来获取图像。要获取图像,我们使用urllib.request.urlretrieve()函数。

  • 我们也使用os.path.join()将图像存储在新创建的目录中,并具有指定的标题名称。

  • 我们使用apod[“hdurl”]来下载镜像。

显示其他信息:

  • 现在我们已经将图像下载到特定目录中,我们将显示图像的其他相关信息。我们检查密钥的具体信息是否存在。如果键存在,那么我们将显示它的值。

  • 然后我们使用Ipython库的Image()函数显示主图。

音频解释:

  • 现在我们的图像和其他信息已经显示出来了,我们将询问用户是否想听图像的解释。如果用户按下*,我们将使用 Google Text to Speech (gtts) 库将文本转换为音频文件。

  • 我们创建一个对象,该对象将要转换的文本、语速和语言作为输入。然后我们将该信息存储在扩展名为.mp3的特定目录中。

  • 然后我们使用Audio()函数来播放我们的 jupyter notebook 中的音频文件。

  • 如果媒体类型不是图像,我们会打印一条短消息说“图像不可用”。

请运行以下 Google Collaboratory 文件以查看正确的输出。您可以在Google Collaboratory上在线下载并运行此代码文件。

根据日期值获取天文图像

但是,如果用户想要获取特定日期的图像怎么办?这很简单!我们不会使用今天的日期,而是以指定格式从用户那里获取日期并将其作为参数传递。这是代码的唯一区别。查看下面的完整内容。

#Import required libraries:
import nasapy
import os
from datetime import datetime
import urllib.request
from IPython.display import Image,display,Audio
from gtts import gTTS

#Initialize Nasa class by creating an object:
nasa = nasapy.Nasa(key="523p5hPYHGzafYGLCkqa54kKMTV2vbP0XcPxkcLm")

#Get today's date in YYYY-MM-DD format:
d = input("Enter date in YYYY-MM-DD format : ")

#Get the image data:
apod = nasa.picture_of_the_day(date=d, hd=True)

#POINT A:
#Check the media type available:
if(apod["media_type"] == "image"):

    #POINT B:
    #Displaying hd images only:
    if("hdurl" in apod.keys()):

        #POINT C:
        #Saving name for image:
        title = d + "_" + apod["title"].replace(" ","_").replace(":","_") + ".jpg"

        #POINT D:
        #Path of the directory:
        image_dir = "Astro_Images"

        #Checking if the directory already exists?
        dir_res = os.path.exists(image_dir)

        #If it doesn't exist then make a new directory:
        if (dir_res==False):
            os.makedirs(image_dir)

        #If it exist then print a statement:
        else:
            print("Directory already exists!\n")

        #POINT E:
        #Retrieving the image:
        urllib.request.urlretrieve(url = apod["hdurl"] , filename = os.path.join(image_dir,title))

        #POINT F:
        #Displaying information related to image:

        if("date" in apod.keys()):
            print("Date image released: ",apod["date"])
            print("\n")
        if("copyright" in apod.keys()):
            print("This image is owned by: ",apod["copyright"])
            print("\n")
        if("title" in apod.keys()):
            print("Title of the image: ",apod["title"])
            print("\n")
        if("explanation" in apod.keys()):
            print("Description for the image: ",apod["explanation"])
            print("\n")
        if("hdurl" in apod.keys()):
            print("URL for this image: ",apod["hdurl"])
            print("\n")

        #POINT G:
        #Displaying main image:
        display(Image(os.path.join(image_dir,title)))

        #Point H:
        #Text to Speech Conversion:
        #Take input from user:
        print("\n")
        choice = input("Press * to hear the audio explanation : ")

        if(choice=="*"):
            #Text to be converted:
            mytext = apod["explanation"]
            #mytext="Good Evening Pratik."

            #Creating an object:
            myobj = gTTS(text=mytext, lang="en", slow=False) 

            #Generating audio file name:
            audio_title = d + "_" + apod["title"] + ".mp3"

            #Save the converted file:
            myobj.save(os.path.join(image_dir,audio_title)) 

            #Name of sound file:
            sound_file = os.path.join(image_dir,audio_title)

            # Playing the converted file 
            display(Audio(sound_file, autoplay=True))



#POINT I:
#If media type is not image:
else:
    print("Sorry, Image not available!")

进入全屏模式 退出全屏模式

请运行以下 Google Collaboratory 文件以查看正确的输出。您可以在Google Collaboratory上在线下载并运行此代码文件。

下载一系列日期的天文图像

现在我们知道如何下载和显示特定日期的图像,是时候进一步推动事情了。我们将下载日期范围的图像,并显示我们下载的随机图像。让我们了解如何在下面实现这一点。

Python实现(9步)

第一步:导入需要的库

这些与我们之前使用的库相同。

These are the same libraries we used previously.
#Import required libraries:
import nasapy
import os
import pandas as pd
import urllib.request
from IPython.display import Image,display

进入全屏模式 退出全屏模式

第二步:创建一个 Nasa 类的对象

在这里,我们将创建一个名为nasa的对象。我们正在使用 nasapy 库和我们注册的 api 密钥。我们将使用该对象调用 Nasa 类的方法来获取有关我们的天文图像的信息。

#Initialize Nasa class by creating an object:

k = "523p5hPYHGzafYGLCkqa54kKMTV2vbP0XcPxkcLm"
nasa = nasapy.Nasa(key = k)

进入全屏模式 退出全屏模式

第三步:获取日期列表

我们希望在多个日期下载多个图像。因此,我们将使用熊猫库的date_range()函数。此函数将为我们提供所需格式的日期列表。在这里,周期值决定了列表的范围。

我们将下载 5 张图像,但您可以通过调整周期和结束值来下载任意数量的图像。

#Get a list of dates:
dates = pd.date_range(end = '2020-08-15', periods=5)

进入全屏模式 退出全屏模式

第四步:获取数据

在前一种情况下,我们只有一个图像。但是在这里,我们将下载许多图像。为此,我们正在创建一个空列表来将所有图像的所有值存储为字典。

首先,我们将获取日期值并将其存储在 apod 变量中。然后我们将获取所需信息作为字典并将其附加到列表中。

#Empty list to store dictionary keys and values:
data = []

#Getting all the data:
for d in dates:
    apod = nasa.picture_of_the_day(d, hd=True)

    if apod['media_type'] == 'image':
        if 'hdurl' in apod.keys():
            data.append({'date':apod['date'], 'title': apod['title'],'hdurl': apod['hdurl']})

进入全屏模式 退出全屏模式

第五步:设置图片存放位置

现在我们将像之前一样创建一个目录来存储图像。

#Path of the directory:
image_dir = "AAA_Images_1"

#Checking if the directory already exists?
dir_res = os.path.exists(image_dir)

#If it doesn't exist then make a new directory:
if (dir_res==False):
    os.makedirs(image_dir)

#If it exist then print a statement:
else:
    print("Directory already exists!\n")  

进入全屏模式 退出全屏模式

第 6 步:下载图像

现在我们有了图像和目录的所有信息,我们将下载图像。我们使用for loop循环遍历列表中的所有数据。

#Retrieving the image:    
for img in data: 



    #Creating title for image:
    title = img["date"]+"_"+img["title"].replace(" ","_").replace(":","_")+".jpg"

    #Downloading the image:
    urllib.request.urlretrieve(img['hdurl'],
os.path.join(image_dir,title))

进入全屏模式 退出全屏模式

第七步:获取图片列表

现在我们已经下载了所有图像,是时候展示它们了。目录中会有很多图片,所以我们可以使用以下代码获取图片列表。

#Get a list of images:
astro_images = os.listdir(image_dir)

进入全屏模式 退出全屏模式

步骤 8:显示图像

现在我们可以使用Image()轻松显示图像。我们将使用os.path.join()来查找图像位置。在这里,我们将显示可用图像列表中的第 _0 个图像。

#Displaying an image:
Image(os.path.join(image_dir, astro_images[0]))

进入全屏模式 退出全屏模式

步骤 9:显示列表中的随机图像

我们可以使用 python 的随机库从可用图像列表中获取随机图像。

#Get random image:
import random
Image(os.path.join(image_dir, astro_images[random.randint(0,len(astro_images)-1)]))

进入全屏模式 退出全屏模式

放在一起

步骤1:

#Import required libraries:
import nasapy
import os
import pandas as pd
import urllib.request
from IPython.display import Image,display

#Initialize Nasa class by creating an object:
k = "523p5hPYHGzafYGLCkqa54kKMTV2vbP0XcPxkcLm"
nasa = nasapy.Nasa(key = k)

#Get a list of dates:
dates = pd.date_range(end = '2020-08-15', periods=5)

#Empty list to store dictionary keys and values:
data = []

#Getting all the data:
for d in dates:
    apod = nasa.picture_of_the_day(d, hd=True)

    if apod['media_type'] == 'image':
        if 'hdurl' in apod.keys():
            data.append({'date':apod['date'], 'title': apod['title'],'hdurl': apod['hdurl']})


#Path of the directory:
image_dir = "AAA_Images_1"

#Checking if the directory already exists?
dir_res = os.path.exists(image_dir)

#If it doesn't exist then make a new directory:
if (dir_res==False):
    os.makedirs(image_dir)

#If it exist then print a statement:
else:
    print("Directory already exists!\n")       


#Retrieving the image:    
for img in data: 

    #Creating title for image:
    title = img["date"]+"_"+img["title"].replace(" ","_").replace(":","_")+".jpg"

    #Downloading the image:
    urllib.request.urlretrieve(img['hdurl'], os.path.join(image_dir,title))

#Get list of images:
astro_images = os.listdir(image_dir)

进入全屏模式 退出全屏模式

第2步:

#Displaying an image:
Image(os.path.join(image_dir, astro_images[0]))

进入全屏模式 退出全屏模式

第 3 步:

#Get random image:
import random
Image(os.path.join(image_dir, astro_images[random.randint(0,len(astro_images)-1)]))

进入全屏模式 退出全屏模式

[Alt](https://res.cloudinary.com/practicaldev/image/fetch/s--yLiDzoTd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev- to-uploads.s3.amazonaws.com/i/cs48x5udbmjndwoabebn.png)

请运行以下 Google Collaboratory 文件以查看正确的输出。您可以在Google Collaboratory上在线下载并运行此代码文件。

结束

恭喜您使用 NASA 的 API 和 Python 完成了这项有趣的活动。我希望这个活动教会了你一些可以用 Python 做的新事情,并激励你继续学习。

在本教程的下一部分中,我们将了解如何通过电子邮件发送下载的图像。

要下载本教程中使用的所有 jupyter 笔记本单击此处。如果您对本文有任何疑问、问题或想法,请随时通过shuklapratik22@gmail.com与我联系

如果您想继续学习 API 并希望将这些技能提升到一个新的水平,请查看 Educative 的课程 Learn REST and SOAP API Test Automation in Java。您将学习如何执行 REST 和 SOAP API 测试自动化,并学习如何从头开始编写 API 和集成测试。

学习愉快!

继续阅读有关 Python 和 API 的信息

  • 通过这 6 个挑战提升您的 Python 技能

  • Java 8 教程:主流 API 及更高版本

  • 用于编码面试的 Python 主算法

Logo

ModelScope旨在打造下一代开源的模型即服务共享平台,为泛AI开发者提供灵活、易用、低成本的一站式模型服务产品,让模型应用更简单!

更多推荐