0
import urllib
import xml.etree.ElementTree as ET
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()

    tree=ET.parse(s)

    current= tree.find("current_condition/condition")
    condition_data = current.get("data")  
    weather = condition_data  
    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()

给出错误,我实际上想从谷歌天气 xml 站点标签中查找值

4

2 回答 2

3

代替

tree=ET.parse(s)

尝试

tree=ET.fromstring(s)

此外,您想要的数据的路径不正确。应该是:天气/current_conditions/condition

这应该有效:

import urllib
import xml.etree.ElementTree as ET
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()

    tree=ET.fromstring(s)

    current= tree.find("weather/current_conditions/condition")
    condition_data = current.get("data")  
    weather = condition_data  
    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)
于 2010-06-17T18:12:14.183 回答
0

我将在这里给出与我在对您之前的问题的评论中所做的相同的答案。将来,请更新现有问题,而不是发布新问题。

原来的

对不起 - 我并不是说我的代码会完全按照你的意愿工作。您的错误是因为 s 是一个字符串并且 parse 需要一个文件或类似文件的对象。因此,“tree = ET.parse(f)”可能会更好。我建议阅读 ElementTree api,以便了解我上面使用的函数在实践中的作用。希望对您有所帮助,并让我知道它是否有效。

于 2010-06-17T18:09:35.920 回答