Pergunta

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

Erro, eu realmente queria encontrar valores do Google Weather XML Site Tags

Foi útil?

Solução

Ao invés de

tree=ET.parse(s)

tentar

tree=ET.fromstring(s)

Além disso, seu caminho para os dados que você deseja está incorreto. Deve ser: clima/current_conditions/condição

Isso deve funcionar:

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)

Outras dicas

Vou dar a mesma resposta aqui que fiz no meu comentário sobre sua pergunta anterior. No futuro, atualize a questão existente em vez de postar uma nova.

Original

Sinto muito - não quis dizer que meu código funcionaria exatamente como você desejava. Seu erro é porque S é uma string e Parse leva um arquivo ou um objeto semelhante a um arquivo. Portanto, "Tree = et.Parse (f)" pode funcionar melhor. Eu sugiro ler a API da ElementTree para que você entenda o que as funções que usei acima fazem na prática. Espero que isso ajude e me avise se funcionar.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top