Introduction

We can use python to develop a program to capture any city’s weather forecast from openweathermap.org web site under our Raspberry Pi computer. I list our program and screen capture result in the following for your reference.

Program Source Code under Python ver 3 as below:

import urllib.request,json

city = input(“Enter City: “)

def getForecast(city) :
    #url = “http://api.openweathermap.org/data/2.5/forecast/daily?cnt=7&units=meteric&mode=json&q=”
    #url = “http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=42443ecbdcad3d01842205e3745895cd”
    #url = “http://api.openweathermap.org/data/2.5/forecast/daily?cnt=7&units=meteric&mode=json&q=LONDON&lang=zh_cn&APPID=42443ecbdcad3d01842205e3745895cd”
    url = “http://api.openweathermap.org/data/2.5/forecast/daily?cnt=7&units=meteric&mode=json&q=”
    url = url + city + “&lang=zh_cn&APPID=42443ecbdcad3d01842205e3745895cd”
    req = urllib.request.Request(url)
    response=urllib.request.urlopen(req)
    return json.loads(response.read().decode(“UTF-8”))

forecast = getForecast(city)

print(“Forecast for “, city, forecast[‘city’][‘country’])

day_num=1
for day in forecast[‘list’]:
    print(“Day : “, day_num)
    print(day[‘weather’][0][‘description’])
    print(“Cloud Cover : “, day[‘clouds’])
    print(“Temp Min : “, round(day[‘temp’][‘min’]-273.15, 1), “degrees C”)
    print(“Temp Max : “, round(day[‘temp’][‘max’]-273.15, 1), “degrees C”)
    print(“Humidity : “, day[‘humidity’], “%”)
    print(“Wind Speed : “, day[‘speed’], “m/s”)
    print()
    day_num = day_num+1

Screen Dump Result as below:

weather-pi

Further Development:

This function can be further developed to save weather forecast data to database, and then display in a chart format on screen. I may do it if I have time in future.

4 thoughts on “How to Capture Weather Forecast from web using Raspberry Pi’s Python Program

  1. Everything is very open with a really clear description of the issues. It was really informative. Your site is extremely helpful. Thank you for sharing!

Leave a Reply

Your email address will not be published.

Enter Captcha Here : *

Reload Image