반응형
weather API 사용하기
openweathermap
Weather API - OpenWeatherMap
Please sign up and use our fast and easy-to-work weather APIs for free. Look at our monthly subscriptions for more options rather than the Free account that we provide you. Read How to start first and enjoy using our powerful weather APIs.
openweathermap.org
openweathermap API를 이용하여 도시별 기상정보를 불러올 수 있습니다.
1. JSON으로 불러오기
import requests
import json
API_KEY = 'API_KEY'
## city_data를 json으로 가져오기
def get_city_data(city_name):
API_URL = f'https://api.openweathermap.org/data/2.5/weather?q={city_name}&units=metric&appid={API_KEY}'
raw_data = requests.get(API_URL)
current_weather = json.loads(raw_data.text)
return current_weather
city_data = get_city_data('Seoul')
print(f"get_city_data('Seoul') : {city_data}")
>>>get_city_data('Seoul') : {'coord': {'lon': 126.9778, 'lat': 37.5683}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': 'scattered clouds', 'icon': '03n'}], 'base': 'stations', 'main': {'temp': 14.38, 'feels_like': 12.63, 'temp_min': 13, 'temp_max': 17, 'pressure': 1015, 'humidity': 29}, 'visibility': 10000, 'wind': {'speed': 2.06, 'deg': 10}, 'clouds': {'all': 40}, 'dt': 1617192233, 'sys': {'type': 1, 'id': 8096, 'country': 'KR', 'sunrise': 1617139160, 'sunset': 1617184381}, 'timezone': 32400, 'id': 1835848, 'name': 'Seoul', 'cod': 200}
2. JSON에서 필요한 데이터를 추출
## json data에서 필요한 정보 가져오기
# weather_description
def get_weather_description(json_data):
weather_description = json_data['weather'][0]['description']
return weather_description
# minimum_temp
def get_minimum_temp(json_data):
temp_min = json_data['main']['temp_min']
return temp_min
weather_description = get_weather_description(city_data)
print(f"city_description('Seoul') : {weather_description}")
minimum_temp = get_minimum_temp(city_data)
print(f"minimum_temp('Seoul') : {minimum_temp}")
>>> city_description('Seoul') : clear sky
>>> minimum_temp('Seoul') : 13
반응형
'인공지능 > 데이터' 카테고리의 다른 글
Flask 시작하기 (0) | 2021.04.01 |
---|---|
트위터 API, tweepy 사용하기 (0) | 2021.03.31 |
Scraping (Beautiful Soup) (0) | 2021.03.16 |
ORM (SQL Alchemy) (0) | 2021.03.16 |
SQL DB with Python 간단사용법 (0) | 2021.03.12 |
댓글