Domanda

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

dà l'errore, io in realtà volevo trovare valori da tag sito di Google tempo xml

È stato utile?

Soluzione

Al posto di

tree=ET.parse(s)

try

tree=ET.fromstring(s)

Inoltre, il percorso per i dati che si desidera non è corretto. Dovrebbe essere: tempo / current_conditions / condizione

Questo dovrebbe funzionare:

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)

Altri suggerimenti

Ti darò la stessa risposta qui ho fatto nel mio commento alla tua domanda precedente. In futuro, aggiornare gentilmente la questione esistente invece di inviare uno nuovo.

originale

Mi dispiace - Non volevo che il mio codice avrebbe funzionato esattamente come si desidera. Il tuo errore è perché s è una stringa e analizzare prende un file o di un oggetto simile a file. Quindi, "albero = ET.parse (f)" può funzionare meglio. Vorrei suggerire la lettura sul api ElementTree in modo da capire quali sono le funzioni che ho usato di cui sopra nella pratica. Speranza che aiuta, e fatemi sapere se funziona.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top