无法使用Python有效地解析XML

时间:2010-06-17 17:58:29

标签: python xml elementtree

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网站标签中找到值

2 个答案:

答案 0 :(得分:3)

而不是

tree=ET.parse(s)

tree=ET.fromstring(s)

此外,您所需数据的路径不正确。它应该是:weather / 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)

答案 1 :(得分:0)

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

Original

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