home.openweathermap.org/ 사용 (서울, 도쿄, 뉴욕 날씨)
import requests
#보통 웹API의 결과는 JSON형식이나 XML형식 리턴을 한다.
#openweather에서는 JSON형식으로 리턴한다.
#따라서, JSON형식의 데이터를 파이썬 데이터 형식으로 변환해줘야 하는데
#이때 json모듈이 필요함.
import json
#API키를 지정한다. 여러분들의 API키를 사용
apikey="키 값"
city_list = ["Seoul,KR", "Tokyo,JP", "New York,US"]
#API 지정
api="http://api.openweathermap.org/data/2.5/weather?q={city}&APPID={key}"
# 켈빈 온도를 섭씨 온도로 변환하는 함수
k2C = lambda k: k - 273.15
#각 도시의 정보를 추출하기
for name in city_list:
#API의 URL 구성하기
url = api.format(city=name, key=apikey)
#API요처을 보내 날씨 정보를 가져오기
res = requests.get(url)
#JSON형식의 데이터를 파이썬형으로 변환한다.
data = json.loads(res.text)
#결과를 출력하기
print("** 도시 = ", data["name"])
print("| 날씨 = ", data["weather"][0]["description"])
print("| 최저기온 = ", k2C(data["main"]["temp_min"]))
print("| 최고기온 = ", k2C(data["main"]["temp_max"]))
print("| 습도 = ", data["main"]["humidity"])
print("| 기압 = ", data["main"]["pressure"])
print("| 풍향 = ", data["wind"]["deg"])
print("| 풍속 = ", data["wind"]["speed"])
print(" ")
기상청 (국내 날씨에 따른 분류)
from bs4 import BeautifulSoup
import urllib.request as req
import os.path
#XML 다운로드
url ="http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108"
fileName = "forecast.xml"
if not os.path.exists(fileName):
req.urlretrieve(url, fileName)
# 다운받은 파일을 분석하기
xml_data = open(fileName, "r", encoding="utf-8").read()
soup = BeautifulSoup(xml_data, 'html.parser')
# 각 지역 확인하기
info = {}
for location in soup.find_all("location"):
cityName = location.find("city").string
weather = location.find("wf").string
if not (weather in info):
info[weather] = []
info[weather].append(cityName)
# 지역의 날씨를 구분해서 분류하기
for weather in info.keys():
print("**", weather)
for name in info[weather]:
print(" - ", name)
반응형
'Python > Python 연습' 카테고리의 다른 글
(Python) 제주도 교통정보 일간 통계 API로 값 뽑기 (0) | 2020.11.12 |
---|---|
(Python) Selenium 연습 : 로그인, 검색 (0) | 2020.11.09 |
(Python) 데이터 시각화 연습 : 웹에서 값 가져오기 (0) | 2020.11.04 |
(Python)성적관리 프로그램 (함수 추가) (0) | 2020.10.15 |
(Python)성적관리 프로그램 (0) | 2020.10.14 |