How do I parse simpleforecast period 1 conditions using python?

  • 1
  • Question
  • Updated 2 years ago
I am trying to use Python to get the conditions from the period 1 of the simpleforecast in the forecast feature. I apparently don't know the syntax for pointing to that specific data. What I am trying right now is:

import urllib2

import json

f = urllib2.urlopen('http://api.wunderground.com/api/my_key/forecast/q/TX/Waco.json')

json_string = f.read()

parsed_json = json.loads(json_string)

todayCondition = parsed_json['simpleforecast']['forecastday']['period'][1]['conditions']

print "Conditions for today are %s" % (todayCondition)

f.close()

I know the issue is with the way I am telling python to find the parsed data I want but I don't know how to get the specific conditions for "period": 1
Photo of Ryan Joyner

Ryan Joyner

  • 2 Posts
  • 1 Reply Like
  • unsure

Posted 2 years ago

  • 1
Photo of Ryan Joyner

Ryan Joyner

  • 2 Posts
  • 1 Reply Like
Nevermind. Figured it out.
In case this helps any other newbies, here is my python code to print the current temp, today's conditions, and today's high temp (all the things I want to know when getting dressed in the morning, haha):

import urllib2

import json

f = urllib2.urlopen('http://api.wunderground.com/api/my_key/conditions/forecast/q/TX/Waco.json')

json_string = f.read()

parsed_json = json.loads(json_string)

currentTemp = parsed_json['current_observation']['temp_f']

todayCondition = parsed_json['forecast']['simpleforecast']['forecastday'][0]['conditions']

todayHigh = parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['fahrenheit']

print "Current temperature is %s. Conditions for today are %s and the high temp will be %s" % (currentTemp, todayCondition, todayHigh)

f.close()

Photo of Ravi Yadav

Ravi Yadav

  • 82 Posts
  • 8 Reply Likes
It's great that you figured it out and thanks for sharing the code with the community. 
Photo of Mark Caesar Casiano

Mark Caesar Casiano

  • 2 Posts
  • 1 Reply Like
Can someone tell me why I'm getting KeyError: 'location'?

I'm using urllib3 to get the html.


def get_json_from_web(province, city):
    wukey = 'some_key_here'
    url = 'http://api.wunderground.com/api/{}/geolookup/conditions/forecast/q/{}/{}.json'.format(wukey,province, city)
    http = urllib3.PoolManager()

    response = http.request('GET', url)
    json_string = response.data.decode('utf8')
    parsed_json = json.loads(json_string)
    print(parsed_json)
    location = parsed_json['location']['city']
    temp_f = parsed_json['current_observation']['temp_f']
    print("Current temperature in %s is: %s" % (location, temp_f))
    response.close()

I app breaks at this code: location = parsed_json['location']['city'] 
Photo of Mark Caesar Casiano

Mark Caesar Casiano

  • 2 Posts
  • 1 Reply Like
fixed. The problem is not having the correct url.