我无法使用python脚本从NASA网站下载数据

时间:2019-06-28 00:43:27

标签: python-2.7 authentication python-requests

我一直在尝试从NASA网站https://search.earthdata.nasa.gov/search下载一组文件。我能够登录并请求文件,但出现错误。

Succesfully logged in
.
.
.
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized

我尝试了请求,wget,urllib2

import requests
import os
import urllib2

destination = r'C:\PROJECTS\ShallowGW\MODIS\\'
os.chdir(destination)

session_req = requests.session()

home_url = 'https://urs.earthdata.nasa.gov/home'
response0 = session_req.get(home_url)

login_url = 'https://urs.earthdata.nasa.gov/login'
login_data = {'authenticity_token': '????',
          'username': '*******',
          'password': '*******'}

response1 = session_req.post(login_url, data=login_data, 
headers=dict(referer=login_url))

try:
    response1.raise_for_status()
    print("Succesfully logged in")
except Exception as e:
    print('Login failed')

response3 = session_req.get('https://search.earthdata.nasa.gov/search')
filepath = r'C:\PROJECTS\ShallowGW\MODIS\MODIS_LST_Links_2016.txt'

with open(filepath) as f_obj:
    for line in f_obj:
        urllib2.urlopen(line)
        print(line)

我不明白为什么它说我登录然后给出401 HTTP错误。文本文件具有下载文件的链接(例如https://e4ftl01.cr.usgs.gov//MODV6_Dal_E/MOLT/MOD11A1.006/2016.06.30/MOD11A1.A2016182.h12v04.006.2016241041516.hdf)。如果我已登录,则可以使用同一行手动下载它们,但不适用于python。它应该经过循环并下载每个文件。 请帮忙!

1 个答案:

答案 0 :(得分:0)

NASA希望您将API密钥包含在请求参数中(基于this网页)。

apiKey = # YOUR API KEY HERE
requestParams = {'api_key':apiKey}

response = requests.get('https://search.earthdata.nasa.gov/search', params = requestParams)

here中列出了其他可能有用的请求参数。我希望这会有所帮助!