ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python 데이터분석 기초 14 - 기상청 제공 날씨정보 XML 자료 읽기
    Python 데이터 분석 2022. 11. 1. 16:57

     

    # 기상청 제공 날씨정보 XML 자료 읽기
    import urllib.request
    from bs4 import BeautifulSoup
    import pandas as pd
    
    url = "http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp"
    data = urllib.request.urlopen(url).read()
    
    soup = BeautifulSoup(data, 'html.parser')
    # print(soup)
    
    print('find method 사용') # find method
    print()
    title = soup.find('title').string
    print(title)
    wf = soup.find('wf').string
    print(wf)
    
    city = soup.find_all('city')
    print(city)
    cityData = []
    for c in city:
        cityData.append(c.string)
        
    df = pd.DataFrame()
    df['city'] = cityData
    print(df.head(3), len(df))
    
    print('select method 사용') # select method
    print()
    tempMins = soup.select('location > province + city + data > tmn') # next sibling
    tempData = []
    for t in tempMins:
        tempData.append(t.string)
        
    df['temp_min'] = tempData # temp_min이라는 컬럼명으로 데이터를 df에 넣는다.
    df.columns = ['지역', '최저기온'] # 칼럼명 바꿀 수 있다.
    print(df.head(3))
    
    df.to_csv('날씨.csv', index = False) # 파일로 저장하기
    print()
    df2 = pd.read_csv('날씨.csv')
    print(df2.head(3)) # 파일의 내용을 불러오기
    
    
    <console>
    C:\anaconda3\lib\site-packages\bs4\builder\__init__.py:545: XMLParsedAsHTMLWarning: It looks like you're parsing an XML document using an HTML parser. If this really is an HTML document (maybe it's XHTML?), you can ignore or filter this warning. If it's XML, you should know that using an XML parser will be more reliable. To parse this document as XML, make sure you have the lxml package installed, and pass the keyword argument `features="xml"` into the BeautifulSoup constructor.
      warnings.warn(
    find method 사용
    
    기상청 육상 중기예보
    ○ (하늘상태) 4일(금)~8일(화)은 전국이 대체로 맑겠으며, 9일(수)~11일(금)은 가끔 구름많겠습니다.<br />○ (기온) 북서쪽에서 찬 공기가 남하하면서 4일(금)~6일(일) 아침 기온은 -2~9도, 낮 기온은 10~18도로 어제(31일, 아침최저기온 6~12도, 낮최고기온 18~21도)보다 낮겠고, <br />          7일(월)부터 기온이 점차 회복되어 11일(금)까지 아침 기온은 1~13도, 낮 기온은 14~20도로 어제와 비슷하거나 조금 낮겠습니다.<br />○ (주말전망) 11월 5일(토)~6일(일)은 전국이 대체로 맑겠습니다. 아침 기온은 -2~8도, 낮 기온은 13~18도가 되겠습니다.<br /><br />* 이번 예보 기간에는 대기가 차차 건조해지겠으니, 산불 등 화재예방에 유의하기 바랍니다.
    [<city>서울</city>, <city>인천</city>, <city>수원</city>, <city>파주</city>, <city>이천</city>, <city>평택</city>, <city>춘천</city>, <city>원주</city>, <city>강릉</city>, <city>대전</city>, <city>세종</city>, <city>홍성</city>, <city>청주</city>, <city>충주</city>, <city>영동</city>, <city>광주</city>, <city>목포</city>, <city>여수</city>, <city>순천</city>, <city>광양</city>, <city>나주</city>, <city>전주</city>, <city>군산</city>, <city>정읍</city>, <city>남원</city>, <city>고창</city>, <city>무주</city>, <city>부산</city>, <city>울산</city>, <city>창원</city>, <city>진주</city>, <city>거창</city>, <city>통영</city>, <city>대구</city>, <city>안동</city>, <city>포항</city>, <city>경주</city>, <city>울진</city>, <city>울릉도</city>, <city>제주</city>, <city>서귀포</city>]
      city
    0   서울
    1   인천
    2   수원 41
    select method 사용
    
       지역 최저기온
    0  서울    1
    1  인천    2
    2  수원    1
    
       지역  최저기온
    0  서울     1
    1  인천     2
    2  수원     1

     

     

    댓글

Designed by Tistory.