我正在尝试从NASA服务器(URL)下载文件(大约1 - 1.5MB /文件),但无济于事!我用urllib2尝试过一些东西并遇到两个结果:
通过“什么都没有”我的意思是当我打开文件(这些是hdf5文件,所以我在hdfView中打开它)我看不到层次结构......字面上看起来像一个空的h5文件。但是,当我在文本编辑器中打开文件时,我可以看到那里有SOMETHING(它是二进制文件,所以在文本中它看起来像......好吧,二进制)。
我认为我正在使用urllib2,尽管之前我从未成功使用过urllib2。请您评论一下我的工作是否正确,并提出更好的建议吗?
from urllib2 import Request, urlopen, URLError, HTTPError
base_url = 'http://avdc.gsfc.nasa.gov/index.php?site=1480884223&id=40&go=list&path=%2FH2O%2F/2010'
file_name = 'download_2.php?site=1480884223&id=40&go=download&path=%2FH2O%2F2010&file=MLS-Aura_L2GP-H2O_v03-31-c01_2010d360.he5'
url = base_url + file_name
req = Request(url)
# Open the url
try:
f = urlopen(req)
print "downloading " + url
# Open our local file for writing
local_file = open('test.he5', "w" + file_mode)
#Write to our local file
local_file.write(f.read())
local_file.close()
except HTTPError, e:
print "HTTP Error:",e.code , url
except URLError, e:
print "URL Error:",e.reason , url
我从here得到了这个脚本(似乎最接近工作) 我不确定file_name应该是什么。我查看了存档的页面源信息,并提取了那里列出的文件名(与网页上显示的文件名不同),这样做会产生1.5MB文件,在hdfview中没有显示任何内容。
答案 0 :(得分:1)
您正在创建无效的网址:
base_url = 'http://avdc.gsfc.nasa.gov/index.php?site=1480884223&id=40&go=list&path=%2FH2O%2F/2010'
file_name = 'download_2.php?site=1480884223&id=40&go=download&path=%2FH2O%2F2010&file=MLS-Aura_L2GP-H2O_v03-31-c01_2010d360.he5'
url = base_url + file_name
你可能意味着:
base_url = 'http://avdc.gsfc.nasa.gov/'
file_name = 'download_2.php?site=1480884223&id=40&go=download&path=%2FH2O%2F2010&file=MLS-Aura_L2GP-H2O_v03-31-c01_2010d360.he5'
下载大文件时,最好使用从文件句柄到文件句柄的缓冲副本:
import shutil
# ...
f = urlopen(req)
with open('test.he5', "w" + file_mode) as local_file:
shutil.copyfileobj(f, local_file)
.copyfileobj
将从open urllib连接高效加载并写入打开的local_file
文件句柄。请注意with
语句,当下面的代码块结束时,它会自动为您关闭文件。