使用python访问USGS-EST服务的经验?

2024-10-17 06:15:03 发布

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

我正在编写python代码,它将被传递给gage ID,然后生成一个REST特定的URL来访问我正在查询的瞬时参数值。我对Python还不熟悉,但在生成URL之前,我已经准备好了代码。你知道吗

我正在使用程序包“urllib”访问URL。但是,这里是它变得模糊不清的地方,我假设我需要保存响应(以WaterML格式)以便稍后在代码中进行消化(使用ElementTree xmlapi)。如果这是真的,请更正如果不是,我该怎么办?你知道吗

########################################################################################
# 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)

如何将响应保存为一个文件,以便以后访问以进行解析?你知道吗


Tags: ofthe代码restidurlparameterparam
1条回答
网友
1楼 · 发布于 2024-10-17 06:15:03

您可以将response直接传递给ElementTreeparse()方法:

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

import sys
root.write(sys.stdout)

与打印到stdout不同,您可能希望使用root.find()等从ElementTree获取数据。你知道吗

整个过程非常容易,因为urllib2响应是一个“类似文件的对象”,在Python中这意味着它可以被读取,ElementTree.parse()接受类似文件的对象。因此,它在两个模块之间非常自然地流动,即使它们彼此一无所知。你知道吗

相关问题 更多 >