Frage

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

gibt Fehler, ich wollte eigentlich Werte von Google Wetter XML Site-Tags finden

War es hilfreich?

Lösung

Anstelle von

tree=ET.parse(s)

Versuch

tree=ET.fromstring(s)

Auch Ihr Weg zum gewünschten Datum ist falsch. Es sollte sein: Wetter / current_conditions / Zustand

Dies sollte funktionieren:

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)

Andere Tipps

Ich werde die gleiche Antwort geben ich hier auf Ihre vorherige Frage in meinem Kommentar tat. In Zukunft die bestehende Frage freundlich aktualisieren, statt einen neuen zu veröffentlichen.

Original-

Es tut mir leid - ich bedeute nicht, dass mein Code genau funktionieren würde, wie Sie gewünscht. Ihr Fehler ist, weil s ist ein String und Parse nimmt eine Datei oder Datei-ähnliches Objekt. Also, "Baum = ET.parse (f)" kann besser funktionieren. Ich würde vorschlagen, auf der ElementTree api lesen, so dass Sie verstehen, was die Funktionen, die ich oben in der Praxis tun verwendet haben. Hoffnung, dass, und lassen Sie mich hilft wissen, ob es funktioniert.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top