我正在编写将传递gage ID的python代码,然后生成一个REST特定的URL来访问我正在查询的瞬时参数值。我是Python的新手,但是已经有了代码来处理URL的生成。
我正在使用'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 + "¶meterCd=" + iq_gage_param
# Check
print(query)
response = urllib2.urlopen(query)
如何将响应保存为文件以便稍后进行解析?
答案 0 :(得分:1)
您可以将response
直接传递给ElementTree
parse()
方法:
import xml.etree.ElementTree as ET
root = ET.parse(response)
import sys
root.write(sys.stdout)
您可能希望使用root.find()
等来从ElementTree
获取数据,而不是打印到stdout。
这一切都很容易,因为urllib2
响应是一个"类文件对象"在Python中意味着可以从中读取,ElementTree.parse()
接受类似文件的对象。所以它在两个模块之间非常自然地流动,即使它们彼此一无所知。