2016-11-08 36 views
0

下載鏈接我要操縱低於:(Python)的操縱URL的某些部分在用戶的請求

http://hfrnet.ucsd.edu/thredds/ncss/grid/HFR/USWC/6公里 /每小時/ RTV/HFRADAR,_US_West_Coast_6km_分辨率,_Hourly_RTV_best.ncd?VAR = U & VAR = v &北= 47.20 &西= -126.3600 &Ë AST = -123.8055 &南= 37.2500 & horizStride = 1個& TIME_START = 2015年11月1日 T00%3A00%3A00Z & TIME_END = 2015年11月3日 T14%3A00%3A00Z & timeStride = 1 & addLatLon =真&接受=的NetCDF

我希望做任何事情中的粗體變量,這樣我就可以問什麼座標和數據集,他們希望用戶。這樣我可以使用這個腳本下載不同的數據集。我也想用相同的變量命名已下載前的新文件:USWC6km20151101-20151103。

我做了一些研究和了解,我可以使用的urllib.parse和urllib2的,但是當我試圖與他們進行實驗,它說:「沒有命名的urllib.parse模塊。」

我可以使用webbrowser.open()下載該文件,但操作的網址是給我的問題

謝謝!!

+0

要打開瀏覽器窗口,其中的鏈接或下載任何與該鏈接點保存到? – mx0

+0

根據您提供的規格,該鏈接會自動開始下載數據。所以基本上我想把它作爲程序中的一個基礎鏈接,並且能夠更改粗體部分,這樣我就可以獲得不同的數據集。用戶只需在鏈接中輸入北,西,東,南數字和其他粗體部分,即可開始下載。 – EagleTamer

回答

0

而不是urllib您可以使用requests模塊,使下載內容更容易。實際工作的部分只有4條線。

# first install this module 
import requests 

# parameters to change 
location = { 
    'part': 'USWC', 
    'part2': '_US_West_Coast', 
    'km': '6km', 
    'north': '45.0000', 
    'west': '-120.0000', 
    'east': '-119.5000', 
    'south': '44.5000', 
    'start': '2016-10-01', 
    'end': '2016-10-02' 
} 

# this is template for .format() method to generate links (very naive method) 
link_template = "http://hfrnet.ucsd.edu/thredds/ncss/grid/HFR/{part}/{km}/hourly/RTV/\ 
HFRADAR,{part2},_{km}_Resolution,_Hourly_RTV_best.ncd?var=u&var=v&\ 
north={north}&west={west}&east={east}&south={south}&horizStride=1&\ 
time_start={start}T00:00:00Z&time_end={end}T16:00:00Z&timeStride=1&addLatLon=true&accept=netcdf" 

# some debug info 
link = link_template.format(**location) 
file_name = location['part'] + location['km'] + location['start'].replace('-', '') + '-' + location['end'].replace('-', '') 
print("Link: ", link) 
print("Filename: ", file_name) 

# try to open webpage 
response = requests.get(link) 
if response.ok: 
    # open file for writing in binary mode 
    with open(file_name, mode='wb') as file_out: 
     # write response to file 
     file_out.write(response.content) 

可能下一步將在包含位置字典的列表中循環運行此循環。或者可能從csv文件中讀取位置。

+0

這可以幫助我很多!我想知道請求的具體內容,以及是否意味着我不需要打開瀏覽器本身來開始下載。 – EagleTamer