RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 885389
Accepted
Tony Stark
Tony Stark
Asked:2020-09-25 20:03:50 +0800 CST2020-09-25 20:03:50 +0800 CST 2020-09-25 20:03:50 +0800 CST

HTTP 错误 403:禁止

  • 772

告诉我如何处理错误?我知道服务器并不想响应我的请求,只是阻止了我。如何绕过它?我正在尝试保存来自 NASA 网站的照片。理论上,一切都应该有效,因为这是 Microsoft DEV330x 课程中的一项任务,它适用于所有人。但看起来美国宇航局已经厌倦了这些要求,他们对学生采取了某种保护措施。

%%writefile apod.py

import argparse
from datetime import date, timedelta
from random import randint
import os
import urllib.request

def parse_command_line():

    parser = argparse.ArgumentParser()
    parser.add_argument("-d",'--date', nargs = 3, metavar = ("month", "day", "year"), action = "store", type = int, help = "month day year formatted date (i.e. 03 28 1998)")
    parser.add_argument ('-s', '--surprise', action = 'store_true', help = 'select a random date for a surprise image')
    parser.add_argument ('-k', '--api_key', action = "store", type = str, help = 'NASA developer key')
    parser.add_argument ('-v', '--verbose', action = 'store_true', help = 'verbose mode')
    args = parser.parse_args()
    return args

def create_date(datelist, surprise):

try:    
    if datelist != None:
        d = date(datelist[2], datelist[0], datelist[1])
        return d
    else:
        if surprise:
            start_date = date(1995,6,16)
            end_date = date.today()
            delta = end_date - start_date
            delta_random = randint(0, delta.days)
            d = date.today() - timedelta(delta_random)
            return d

        else: 
            end_date = date.today()
            d = date.today() - timedelta(days = 1) 
            return d

except :
    return None

def query_url(d, api_key):
    global date_obj
date_obj = d.strftime("%Y-%m-%d")
URL = "https://api.nasa.gov/planetary/apod?api_key={}&date={}"
complete_URL = URL.format(api_key,date_obj)
return complete_URL


def save_image(d, image):


year = d.strftime("%Y")
month = d.strftime("%m")
file_path = year+"/"+month+"/"+date_obj+".jpg"
open(file_path, 'wb')
return file_path



def request(url):


# request the content of url and save the retrieved binary data
with urllib.request.urlopen(url) as response:
    data = response.read()

# convert data from byte to string
data = data.decode('UTF-8')

# convert data from string to dictionary
data = eval(data)
return data

def download_image(url):

# request the content of url and return the retrieved binary image data
with urllib.request.urlopen(url) as response:
    image = response.read()
return image

def main():
# NASA developer key (You can hardcode yours for higher request rate limits!)
API_KEY = "cZX0zRDveiz7AfGfOW23typMH3NCnS3uvQJc0ZNS"

# parse command line arguments
args = parse_command_line()

# update API_KEY if passed on the command line
print(args.api_key)
if args.api_key != '':
    API_KEY = args.api_key

# create a request date
d = create_date(args.date, args.surprise)

# ascertain a valid date was created, otherwise exit program
if d is None:
    print("No valid date selected!")
    exit()

# verbose mode
if args.verbose:
    print("Image date: {}".format(d.strftime("%b %d, %Y")))

# generate query url
url = query_url(d, API_KEY)

# verbose mode    
if args.verbose:
    print("Query URL: {}".format(url))

# download the image metadata as a Python dictionary
metadata = request(url)

# verbose mode    
if args.verbose:
    # display image title, other metadata can be shown here
    print("Image title: {}".format(metadata['title']))

# get the url of the image data from the dictionary
image_url = metadata['url']

# verbose mode    
if args.verbose:
    print("Downloading image from:", image_url)

# download the image itself (the returned info is binary)
image = download_image(image_url)

# save the downloaded image into disk in (year/month)
# the year and month directories correspond to the date of the image (d)
# the file name is the date (d) + '.jpg'
save_image(d, image)

print("Image saved")

if __name__ == '__main__':
main()
python-3.x
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    Axenow
    2020-09-28T09:48:26+08:002020-09-28T09:48:26+08:00

    更正这段代码,就是这样:

    # update API_KEY if passed on the command line
    print(args.api_key)
    if args.api_key:
        API_KEY = args.api_key
    

    您只是没有正确检查,因此在 complete_url 您收到 None 而不是密钥。

    • 4

相关问题

  • 使用 vk api,qthread (PyQt5)

  • 如何将元组(带字符串)变成一个字符串并在其中交换单词

  • Python 重用输入

  • PyQt5 缺少参数错误

  • 将参数列表传递给类构造函数

  • 循环跟踪的迭代

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    JavaScript需要一点帮助[重复]

    • 1 个回答
  • Marko Smith

    获取 PHP 脚本的结果

    • 2 个回答
  • Marko Smith

    如何检查 JSON 中是否存在元素?Python

    • 2 个回答
  • Marko Smith

    这样的 typedef 是如何工作的?

    • 3 个回答
  • Marko Smith

    关闭对php页面的访问

    • 1 个回答
  • Marko Smith

    jQuery通过attr获取属性

    • 1 个回答
  • Marko Smith

    用给定字符替换 std::string 中的所有字符

    • 3 个回答
  • Marko Smith

    在多维数组中只保留唯一元素

    • 2 个回答
  • Marko Smith

    你能告诉我如何为 JSON 反序列化创建一个类吗?[复制]

    • 1 个回答
  • Marko Smith

    使用 volatile 关键字重载方法

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0800 CST
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0800 CST
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0800 CST
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0800 CST
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0800 CST
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0800 CST
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0800 CST
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0800 CST
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0800 CST
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0800 CST

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5