Skip to content Skip to sidebar Skip to footer

Can't Parse XML Effectively Using Python

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)

Solution 1:

Instead of

tree=ET.parse(s)

try

tree=ET.fromstring(s)

Also, your path to the data you want is incorrect. It should be: weather/current_conditions/condition

This should work:

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)

Solution 2:

I'll give the same answer here I did in my comment on your previous question. In the future, kindly update the existing question instead of posting a new one.

Original

I'm sorry - I didn't mean that my code would work exactly as you desired. Your error is because s is a string and parse takes a file or file-like object. So, "tree = ET.parse(f)" may work better. I would suggest reading up on the ElementTree api so you understand what the functions I've used above do in practice. Hope that helps, and let me know if it works.


Post a Comment for "Can't Parse XML Effectively Using Python"