0
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 サイトタグから値を見つけたかったのです

4

2 に答える 2

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)
于 2010-06-17T18:12:14.183 に答える
0

ここでは、前の質問に対するコメントで行ったのと同じ回答をします。今後は、新しい質問を投稿する代わりに、既存の質問を更新してください。

オリジナル

申し訳ありませんが、私のコードがご希望どおりに機能するという意味ではありませんでした。あなたのエラーは、 s が文字列であり、 parse がファイルまたはファイルのようなオブジェクトを取るためです。したがって、「tree = ET.parse(f)」の方がうまくいくかもしれません。上記で使用した関数が実際に何をするかを理解できるように、ElementTree API を読むことをお勧めします。それがうまくいくかどうか教えてください。

于 2010-06-17T18:09:35.920 に答える