Python urllib无法自动进行身份验证,在NASA上接收到302错误

2024-04-27 00:43:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用nasagsfc服务器从他们的档案中检索数据。 我以简单的文本形式发送请求并接收响应。在

我发现他们修改了自己的页面,因此需要登录。 然而,我收到一个错误。在

我阅读线程how do python capture 302 redirect url中提供的信息 以及尝试使用urllib2和请求库,但仍然收到错误。在

目前我负责下载数据的部分代码如下所示:

def getSampleData():
    import urllib
    # I approved application according to:
    # http://disc.sci.gsfc.nasa.gov/registration/authorizing-gesdisc-data-access-in-earthdata_login
    # Query: http://hydro1.sci.gsfc.nasa.gov/dods/_expr_{GLDAS_NOAH025SUBP_3H}{ave(rainf,time=00Z23Oct2016,time=00Z24Oct2016)}{17.00:25.25,48.75:54.50,1:1,00Z23Oct2016:00Z23Oct2016}.ascii?result
    sample_query = 'http://hydro1.sci.gsfc.nasa.gov/dods/_expr_%7BGLDAS_NOAH025SUBP_3H%7D%7Bave(rainf,time=00Z23Oct2016,time=00Z24Oct2016)%7D%7B17.00:25.25,48.75:54.50,1:1,00Z23Oct2016:00Z23Oct2016%7D.ascii?result'

    # I've tried also:
    # sock=urllib.urlopen(sample_query, urllib.urlencode({'username':'MyUserName','password':'MyPassword'}))
    # but I was still asked to provide credentials, so I simplified mentioned line to just:
    sock=urllib.urlopen(sample_query)
    print('\n\nCurrent url:\n')
    print(sock.geturl())
    print('\nIs it the same as sample query?')
    print(sock.geturl() == sample_query)
    returnedData=sock.read()
    # returnedData always stores simple page with 302. Why? StackOverflow suggests that urllib and urllib2 handle redirection automatically
    sock.close()

    with open("Output.html", "w") as text_file:
        text_file.write(returnedData)

result page with 302 error

在输出.html内容如下:

{<1分$

如果我将粘贴示例查询(从上面定义的函数中复制sample_query)复制到browser,则接收数据没有问题。 因此,如果解决方案没有希望,我会考虑重写代码以使用Selenium。在


Tags: to数据samplehttptime错误urllibquery