我正在嘗試從 Nasa 的 APOD API 獲取影像并將其保存到我的計算機,但是當請求被發送時,我收到 SSL 證書錯誤。我不知道如何解決它,因為我以前從未處理過這個問題。
這就是我得到的:
raise SSLError(e)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1124)
這是我的代碼:
import nasapy
import os
from datetime import datetime
import urllib.request
from IPython.display import Image,display,Audio
import ssl
def nasa_apod(ctx):
key = "#####################"
nasa = nasapy.Nasa(key=key)
dtm = datetime.today().strftime("%Y-%m-%d")
apod = nasa.picture_of_the_day(date=dtm, hd=True)
print(apod)
if apod["media_type"] == "image":
title = dtm "_" apod["title"].replace(" ", "_").replace(":", "_") ".jpg"
image_dir = "Astro_images"
dir_res = os.path.exists(image_dir)
if dir_res == False:
os.makedirs(image_dir)
else:
print("Directory already exists! ")
filename =os.path.join(image_dir, title)
with urllib.request.urlopen(url=apod["hdurl"], context=ctx) as u, \
open(filename, 'wb') as f:
f.write(u.read())
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")
display(Image(os.path.join(image_dir, title)))
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
nasa_apod(ctx)
出于安全原因,我隱藏了密鑰。
任何幫助表示贊賞!
uj5u.com熱心網友回復:
在呼叫方法之前,您需要替換urllib.request.urlretrieve并urllib.request.urlopen確定自定義ssl背景關系nasa_apod,那么您的程式應如下所示:
def nasa_apod(ctx):
key = "#####"
nasa = nasapy.Nasa(key=key)
dtm = datetime.today().strftime("%Y-%m-%d")
apod = nasa.picture_of_the_day(date=dtm, hd=True)
print(apod)
if apod["media_type"] == "image":
title = dtm "_" apod["title"].replace(" ", "_").replace(":", "_") ".jpg"
image_dir = "Astro_images"
dir_res = os.path.exists(image_dir)
if dir_res == False:
os.makedirs(image_dir)
else:
print("Directory already exists! ")
filename=os.path.join(image_dir, title)
with urllib.request.urlopen(url=apod["hdurl"], context=ctx) as u, \
open(file_name, 'wb') as f:
f.write(u.read())
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")
display(Image(os.path.join(image_dir, title)))
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
nasa_apod(ctx)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/436299.html
上一篇:MQTTTLS連接
