'html 파싱'에 해당되는 글 2건

  1. 2013.04.18 날씨 가져오는 스크립트의 수정 1
  2. 2013.04.17 날씨 가져오는 스크립트
Programming/Python2013. 4. 18. 05:50

지난번에 아주 단순 무식하게 HTML을 파싱해서 날씨 가져오는 스크립트를 포스팅 한 적이 있었는데,

도저히 코드를 봐줄 수도 없고.. 심지어 그 코드에는 심각한 문제가 있었다!

(문제는 비밀입니다.. 궁금하신분은 한번 알아보세요ㅋ 힌트는 리눅스의 권한)


어쨌든 그래서 새로운 코드를 다시 짜 보았다.

역시 코드가 딱히 마음에 들진 않지만.. BeautifulSoup을 처음으로 사용하는 거라 그렇다고 위안말도안되는 변명을 하며....


#!/usr/bin/env python
#-*- coding:utf-8 -*-

import urllib
from BeautifulSoup import BeautifulSoup
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['cond']
    print 'Temparature: ' + result['temp'] + u"\N{DEGREE SIGN}" + 'C'
    print 'RealFeel: ' + result['realfeel'] + u"\N{DEGREE SIGN}" + 'C'
    print result['humid']
    print result['cloud']
    print

def main():
    html = urllib.urlopen("http://www.accuweather.com/en/kr/seoul/226081/current-weather/226081")
    soup = BeautifulSoup(html)

    soup = soup.find('div', {'id':'detail-now'})

    result = {}

    while soup:
        if soup.get('class') == 'cond':
            result['cond'] = soup.text
        elif soup.get('class') == 'temp':
            result['temp'] = soup.text.replace("°", "")
        elif soup.get('class') == 'realfeel':
            s = soup.text.replace("°", "")
            result['realfeel'] = s.replace("RealFeel® ", "")
        elif soup.get('cellspacing') == None and soup.get('class') == 'stats':
            ss = soup.findAll('li')
            for li in ss:
                if 'Humid' in li.text:
                    result['humid'] = li.text.replace(":", ": ")
                elif 'Cloud' in li.text:
                    result['cloud'] = li.text.replace(":", ": ")
            break

        soup = soup.findNext()

    display(result)


if __name__ == "__main__":
    try:
        main()
    except:
        traceback.print_exc()

뭐 어찌됐든 쓸데없는 쓰레기 파일을 만들지도 않고... 더 고치기는 너무 귀찮으니 BeautifulSoup 라이브러리는 언젠가 나중에 더 익숙해지기로 하고 일단 저렇게 써야겠다.


날씨를 가져오는 accuweather.com 해당 페이지의 사이즈가  커서 여전히 속도 문제는 어쩔 수 없는듯하다.


인터넷을 연결해야하는데다가 외국 사이트라 느린 것도 같지만 분단위로 날씨를 업데이트! 해주니 그걸로 만족해야겠다.

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

A* algorithm implementation  (1) 2013.06.14
pygame 설치  (0) 2013.05.02
날씨 가져오는 스크립트  (0) 2013.04.17
쉬워 보이는 언어 Python  (0) 2011.12.27
점프 투 파이썬(Jump to Python)  (0) 2011.12.20
Posted by Tanto
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