Не могу разобрать XML эффективно используя Python - PullRequest
0 голосов
/ 17 июня 2010
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()

выдает ошибку, я действительно хотел найти значения из тегов сайта Google Weather xml

Ответы [ 2 ]

3 голосов
/ 17 июня 2010

Вместо

tree=ET.parse(s)

try

tree=ET.fromstring(s)

Кроме того, ваш путь к нужным данным неверен.Это должно быть: погода / current_conditions / условие

Это должно работать:

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)
0 голосов
/ 17 июня 2010

Я дам тот же ответ, что и здесь, в своем комментарии к вашему предыдущему вопросу.В будущем, пожалуйста, обновите существующий вопрос вместо публикации нового.

Оригинал

Извините, я не имел в виду, что мой код будет работатьименно так, как вы хотели.Ваша ошибка в том, что s является строкой, а parse принимает файл или подобный файлу объект.Таким образом, «tree = ET.parse (f)» может работать лучше.Я бы посоветовал прочитать API-интерфейс ElementTree, чтобы вы понимали, какие функции, которые я использовал выше, выполняют на практике.Надеюсь, что это поможет, и дайте мне знать, если это работает.

...