How to get weather of any city using python

Shashankk
2 min readDec 23, 2019
Photo by Johannes Plenio on Unsplash

Web scraping is one my favourite topic and with python its easy to scrap the web

in this i have build a app which will give you weather of any city i am going to scrap data from open weather API which allow to use it upto certain limits for that you need a API key you can get it from this website

lets import all required modules

import socketimport requests

now create try except block

just to make sure if site is available program will return 200 as status which simply means site is online.

using requests.get() method we can request api using api key

try:socket.create_connection(("www.google.com",80))print("u r connected")city = input("enter city name: ")a1 = "http://api.openweathermap.org/data/2.5/weather?"a2 = "q=" +city + "&units=metric"a3 = "&APPID=fa531e4e62b7ffeb91c7ea854ddf347a"api_address = a1+a2+a3res1 = requests.get(api_address)print(res1)d = res1.json()d1=d['main']['temp']print("temperature =",d1)except OSError as e:print("issue ",e)

API returns lot of information as result in JSON format like this

{'coord': {'lon': 73.85, 'lat': 18.52}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'light rain', 'icon': '10n'}], 'base': 'model', 'main': {'temp': 24.83, 'feels_like': 24.56, 'temp_min': 24.83, 'temp_max': 24.83, 'pressure': 1013, 'humidity': 58, 'sea_level': 1013, 'grnd_level': 941}, 'wind': {'speed': 3.22, 'deg': 139}, 'rain': {'3h': 0.19}, 'clouds': {'all': 100}, 'dt': 1577109915, 'sys': {'country': 'IN', 'sunrise': 1577064773, 'sunset': 1577104428}, 'timezone': 19800, 'id': 1259229, 'name': 'Pune', 'cod': 200}

we need to filter it out to get specific value by ‘ d1=d[‘main’][‘temp’] ’ i am interested to know temperature of Pune

output: temperature will be in Celsius

output
temperature = 24.83

--

--

Shashankk
0 Followers

Engineering student who loves coding