【发布时间】:2010-06-17 15:52:15
【问题描述】:
我正在使用谷歌网站检索天气信息,我想在 XML 标记之间查找值。以下代码给了我一个城市的天气状况,但我无法获得其他参数,例如温度,如果可能的话,解释代码中隐含的拆分函数的工作:
import urllib
def getWeather(city):
#create google weather api url
url = "http://www.google.com/ig/api?weather=" + urllib.quote(city)
try:
# open google weather api url
f = urllib.urlopen(url)
except:
# if there was an error opening the url, return
return "Error opening url"
# read contents to a string
s = f.read()
# extract weather condition data from xml string
weather = s.split("<current_conditions><condition data=\"")[-1].split("\"")[0]
# if there was an error getting the condition, the city is invalid
if weather == "<?xml version=":
return "Invalid city"
#return the weather condition
return weather
def main():
while True:
city = raw_input("Give me a city: ")
weather = getWeather(city)
print(weather)
if __name__ == "__main__":
main()
谢谢
【问题讨论】:
-
参见相关的stackoverflow.com/questions/3106480了解基于XML解析器使用的解决方案
标签: python