Programming/Python2013. 4. 17. 02:05

옛날에 쓰던 개인 노트북을 서버로 만든 후 이것 저것 잡다한 것들을 하다보니, 문득 날씨 정보를 가져오고 싶은 생각이 들었다.


이미 우분투에는 weather-util 이라는 유틸리티를 apt-get으로 받을 수 있기도 하고, 다른 많은 사람들이 펄이라거나 기타등등의 것들로 많이 개발해 두었지만, 내 힘으로 직접 해보고 싶었다.


그래서 아래와 같은 쓰레기코드 ...가 탄생했다...(와 지금 다시봐도 아주 허접하네;;...)


#!/usr/bin/env python

import os
import re
import traceback
from time import localtime, strftime

def display(result):
    print
    print 'Weather in Seoul, Asia at ' + strftime('%H:%M', localtime()) + '\n'
    print 'Condition: ' + result['Condition']
    print 'Temparature: ' + result['Temparature'] + u"\N{DEGREE SIGN}" + 'C'
    print 'RealFeel: ' + result['RealFeel'] + u"\N{DEGREE SIGN}" + 'C'
    print 'Humidity: ' + result['Humidity']
    print 'Cloud Cover: ' + result['Cloud Cover']
    print

def parse(lines):
    result = dict()
    lines = lines.split('\n')
    for line in lines:
        if 'cond' in line:
            result['Condition'] = line[line.find('cond')+6:line.find('</span>')]
            result['Temparature'] = line[line.find('temp')+6:line.find('<span>°')]
            result['RealFeel'] = line[re.search('RealFeel.*; ', line).end():line.find('<span>°</span></span> </div>')]
        elif 'Humidity' in line:
            result['Humidity'] = line[line.find('strong')+7:line.find('</strong')]
        elif 'Cloud Cover' in line:
            result['Cloud Cover'] = line[line.find('strong')+7:line.find('</strong')]

    return result

def main():
    os.system("w3m -dump_source -no-cookie http://www.accuweather.com/en/kr/seoul/226081/current-weather/226081 > /var/tmp/currentweather.gz")
    os.system("gunzip -cf /var/tmp/currentweather.gz > /var/tmp/currentweather.tmp")

    fp = open("/var/tmp/currentweather.tmp", "r")
    lines = fp.readlines()
    fp.close()

    result = ""
    flag = False

    for line in lines:
        if '<div class="info"> <span' in line:
            result = result + line

        if flag:
            if '</ul>' in line:
                flag = False
            else:
                result = result + line

        if '<ul class="stats">' in line:
            flag = True

    display(parse(result))

if __name__ == '__main__':
    try:
        main()
    except:
        print "Error... Sorry"
        traceback.print_exc()

w3m 브라우저의 -dump를 이용해서 페이지 덤프 후 그냥 노가다로 필요한 부분만 긁어내는 것 뿐이다.

그런데 dump를 하면 그 파일이 이유는 모르겠지만 gz로 압축된 파일이어서...;; gunzip으로 압축도 풀고...

어쨌든 그래서 잘 작동은 하지만 좀 느리다... 날씨정보 띄워주는데까지 빠르면 0.5초 ~ 느리면 1.5초 정도까지 걸리는 것 같다.


아무튼 저러던 차에.. 아래 링크를 발견하게 되었다.


Beautiful Soup 라이브러리 포스팅


위와같은 저런 노가다 하지않고.. 라이브러리를 통해서 정상적인 HTML 파서를 나중에 한번 짜봐야겠다.


'Programming > Python' 카테고리의 다른 글

A* algorithm implementation  (1) 2013.06.14
pygame 설치  (0) 2013.05.02
날씨 가져오는 스크립트의 수정  (1) 2013.04.18
쉬워 보이는 언어 Python  (0) 2011.12.27
점프 투 파이썬(Jump to Python)  (0) 2011.12.20
Posted by Tanto