'parsing'에 해당되는 글 1건

  1. 2012.07.06 [Hpple Parser] HTML Parser - 파싱하기
Hpple2012. 7. 6. 13:29

(모든 사진들은 클릭하여 원본크기로 보실수 있습니다.)


파싱하려는 사이트는 기상청(http://www.kma.go.kr/index.jsp)입니다.

날씨가 아닌 국외 지진목록(http://www.kma.go.kr/weather/earthquake/internationallist.jsp)을 파싱해보겠습니다.

================================================================================


뷰컨트롤러를 추가합니다.








ParserHppleAppDelegate.h 로 갑니다.



#import "FirstViewController.h"

===============================================================================

만들어준 FirstViewController를 참조합니다. 


ParserHppleAppDelegate.m


FirstViewController *fView = [[FirstViewController allocinit];

[self.window addSubview:fView.view];

================================================================================

FirstViewController클래스의 인스턴스를 가리키는 fView 인스턴스 변수를 만듭니다.

init메서드를 이용해서 객체를 초기화 시킵니다.


FirstViewController.h



#import <UIKit/UIKit.h>
#import "TFHpple.h"

@interface FirstViewController : UIViewController {
    
}

- (void)connectWebsite;

@end

================================================================================

#import "TFHpple.h"

Hpple를 사용하기위해 임포트 시킵니다.


- (void)connectWebsite;

홈페이지와 통신을 위한 메서드를 하나 만들어줍니다.


FirstViewController.m


#import "FirstViewController.h"

@implementation FirstViewController

- (id)init {
    self = [super init];
    if (self != nil) {
        [self connectWebsite];
    }
    return self;
}

- (void)connectWebsite {
    NSLog(@"connectWebsite");
    
    NSString *htmlURL = [NSString stringWithContentsOfURL:
                         [NSURL URLWithString:@"http://www.kma.go.kr/weather/earthquake/internationallist.jsp"encoding:-2147481280 error:nil];
    NSData *htmlData = [htmlURL dataUsingEncoding:NSUnicodeStringEncoding];
    if (htmlData != nil) {
        TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
        NSArray *parserArray  = [xpathParser search:@"//*"];
        for (int i = 0; i < [parserArray count]; i++) {
            TFHppleElement *element = [parserArray objectAtIndex:i];
            NSLog(@"%@", [element content]);
        }
    }
    else {
        UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"연결 실패"
                                                        message:@"데이터를 가져올 수 없습니다."
                                                       delegate:self cancelButtonTitle:@"확인" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    NSLog(@"connectWebsiteEnd");
}

===============================================================================

- (id)init {
    self = [super init];
    if (self != nil) {
        [self connectWebsite];
    }
    return self;
}

초기화 시키는 메서드입니다.

self(자신)를 super로 init(초기화) 시킨뒤에 self가 nil이 아닐때, 즉 성공적으로 초기화가 됬을때 connectWebsite를 불러줍니다.

그후 self를 반환합니다.


- (void)connectWebsite {
    NSLog(@"connectWebsite");

성공적으로 connectWebsite가 불려졌다면 로그를 찍어확인합니다.


NSString *htmlURL = [NSString stringWithContentsOfURL:
                         [NSURL URLWithString:@"http://www.kma.go.kr/weather/earthquake/internationallist.jsp"encoding:-2147481280 error:nil];

"http://www.kma.go.kr/weather/earthquake/internationallist.jsp"라는 스트링을 NSURL형식으로 변환해준뒤, 다시 NSString형식의stringWithContentsOfURL메소드로 encoding과 error를 넣어서 변환합니다.


NSData *htmlData = [htmlURL dataUsingEncoding:NSUnicodeStringEncoding];

위에서 만들어준 htmlURL를 dataUsingEncoding:NSUnicodeStringEncoding사용해서 htmlData에 넣어줬습니다.


if (htmlData != nil) {
        TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
        NSArray *parserArray  = [xpathParser search:@"//*"];
        for (int i = 0; i < [parserArray count]; i++) {
            TFHppleElement *element = [parserArray objectAtIndex:i];
            NSLog(@"%@", [element content]);
        }

}

htmlData가 nil이 아닐경우(통신에 성공해서 데이터를 받아왔을경우), 

htmlData를 TFHpple의 initWithHTMLData메서드로 xpathParser에 넣어줍니다.

NSArray를 하나 만들어준뒤에 xpathParser에 들어간 자료로 파싱을 시작합니다.

지금은 @"//*"로 서치를 하기때문에 필요한 자료이외에 가비지들도 보여집니다.


만들어진 NSArray를 for문으로 돌려서 TFHppleElement로 설정해준 엘레멘트를 뽑아냅니다.

이걸 로그로 출력하면 다음과같은 결과를 얻을수 있습니다.



스크롤을 올려보시면 위에값도 확인하실수 있는데요, 스샷에 보이는 부분이 http://www.kma.go.kr/weather/earthquake/internationallist.jsp 페이지의 제일 하단과 같음을 확인하실수 있습니다.


else {
        UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"연결 실패"
                                                        message:@"데이터를 가져올 수 없습니다."
                                                       delegate:self cancelButtonTitle:@"확인" otherButtonTitles:nil];
        [alert show];
        [alert release];

}

통신이 실패했을경우 UIAlertView를 띄워 유저가 알수있게 합니다.


NSLog(@"connectWebsiteEnd");

NSLog로 메소드의 끝을 확인합니다.


===============================================================================

이제 해당 페이지소스를 보면서 NSArray *parserArray  = [xpathParser search:@"//*"];에 search:@"//*" 부분을 손봐주면 필요한 자료만 뽑을수 있게 됩니다.


2장끗...

Posted by 다오나무