2014-12-19 28 views
0

我正在寫python代碼,它將傳遞gage ID(s),然後生成一個REST特定的URL來訪問我查詢的瞬時參數值。我是Python的新手,但已經獲得了代碼工作到URL的生成。使用python訪問USGS EST服務的經驗?

我正在使用包'urllib'來訪問該URL。但是,這裏是它變得模糊的地方,我假設我需要保存響應(以WaterML格式)以稍後在代碼中消化(使用ElementTree XML API)。如果這是真的,請更正,如果沒有,我該怎麼辦?

######################################################################################## 
# Bulding the USGS REST query using the gage ID 
# Below is temporary overwriting of gage_Id to be that of the of the gage on the Kanawha river by Charleton, WV 
gage_ID = "03198000" 
# the parameter id of the instantaneous discharge parameter 
iq_gage_param = "00060" # the parameter Id for instantaneous dischagre values form a gage 
# we could list other params and tack them onto the end of the query with a comma "," in between them 

query = "http://waterservices.usgs.gov/nwis/iv?format=waterml,2.0&sites=" + gage_ID + "&parameterCd=" + iq_gage_param 
# Check 
print(query) 

response = urllib2.urlopen(query) 

如何保存的響應爲一個文件以後可以用於分析訪問?

+0

這聽起來像你需要寫一些代碼。一旦你這樣做,隨時發佈它與任何問題,你有。 – 2014-12-19 04:31:43

+0

讓我知道你是否需要更多? – traggatmot 2014-12-19 04:34:12

回答

1

您可以直接傳遞到responseElementTreeparse()方法:

import xml.etree.ElementTree as ET 
root = ET.parse(response) 

import sys 
root.write(sys.stdout) 

而不是打印到stdout,你可能想使用root.find()等來從ElementTree數據。

這整個事情很容易工作,因爲urllib2響應是一個「類文件對象」,它在Python中意味着它可以讀取,並且ElementTree.parse()接受類似文件的對象。所以它在兩個模塊之間很自然地流動,即使他們對彼此一無所知。