굳이 메쉬업 프로그래밍을 하지 않더라도 하다보면 인터넷에서 자료를 쭉 긁어오고 싶을때가 있다.
이건 사실은 신문사 만화 사이트를 일일이 클릭해가면서 - 게다가 그 수많은 광고를 참으며 - 보느니
로컬에 그림만 다운로드 받아봐야지 하고 후다닥 만들었다-ㅅ-


이 작업을 하려면 먼저 bleujin Framework core의 jar 파일을 아래 포스팅에서 다운로드 받고..


위 3개의 jar가 추가적으로 필요하다. 예전에 작성할때 다운로드 받은거라 최근에는 버전업이 됐겠지만 그냥 쓴다-ㅅ-
아마 common-io랑 common-lang도 필요하겠지만 그건 그냥 apache 에서 다운로드 추천-ㅅ-
(오늘까지 방문자가 한명도 없으니 다소 무책임해도 상관없으리라.. 쿨럭)

Framework에는 html Parsing에 관련된 - jericho의 소스에 Facade 패턴을 사용해서 간단하게 만들 수 있었다. - 부분만 있어서 먼저 인터넷에 접속해서 InputStream을 받아오는 로직을 작성해야 한다.



public class Spider {

 private Logger log = LogBroker.getLogger(Spider.class) ;
 
 public Reader getPageContent(String httpURL) throws HttpException, IOException {
  String content = IOUtils.toString(getInputStream(httpURL), "EUC-KR") ;
  return new StringReader(content) ;
 }

 public InputStream getInputStream(String httpURL) throws HttpException, IOException {
  HttpClient httpclient = new HttpClient();
  GetMethod httpget = new GetMethod(httpURL);
  try {

   httpclient.executeMethod(httpget);
   log.info("recevied data : " + httpURL) ;
   
   InputStream input = httpget.getResponseBodyAsStream() ;
   InputStream result = new ByteArrayInputStream(IOUtils.toByteArray(input)) ;
   input.close() ;
   return result ;
   
  } catch (Exception ex) {
   log.warning(ex.getMessage()) ;
   throw new HttpException(ex.getMessage(), ex) ;
  } finally {
   httpget.releaseConnection() ;
  }
 }
}

EUC-KR의 상수 부분이 걸리긴 하지만 머 대충 만들고 넘어가자-ㅅ-(사실 사이트를 제대로 만들었다면 EUC-KR은 요즘의 국제화 시대에 맞지 않는 인코딩방법이다. )

사용은 대충 아래와 같이 한다.

 public void testSportChosun() throws Exception {
  String httpURL = "http://manhwa.sportschosun.com/enter/cartoon/juyu/cartoon_juyu2.asp?num=138&title=juyu&Direct=Next" ;
  Spider s = new Spider() ;
  Reader content = s.getPageContent(httpURL) ;
  HTag tag = HtmlParser.parse(content) ;
  
  HTag img = tag.findElementBy(IMG, "src", "http://manhwa.sportschosun.com/enter/cartoon/juyu/image_cartoons/20071119y_233.gif") ;
  System.out.println(img.toString());
  System.out.println(img.getPath());
  
  
  String imgPath = img.getAttributeValue("src") ;
  System.out.println(imgPath);
  
  content.close() ;
 }


 public void testSave() throws Exception {

  int current = 100 ;
  Spider s = new Spider() ;
  for (int i = 1; i <= current; i++) {
   String path = "http://manhwa.sportschosun.com/enter/cartoon/juyu/cartoon_juyu2.asp?num=" + i + "&title=juyu&Direct=Next" ;
   Reader content = s.getPageContent(path) ;
   HTag tag = HtmlParser.parse(content) ;
   HTag img = tag.getChild("body[0]/table[4]/tr[0]/td[2]/table[1]/tr[8]/td[0]/img[0]") ; // /html/body/table/tr/td/table/tr/td/img
   String imgSrc = img.getAttributeValue("src");
   
   FileOutputStream output = new FileOutputStream(new File("c:/temp/" + StringUtil.substringAfterLast(imgSrc, "/")));
   IOUtils.copy(s.getInputStream(imgSrc), output) ;
   output.close() ;
  }
 }


HTag가 클래스가 Facade 클래스인데 이런저런 다양한 파싱에 관련된 메소드들을 모두 가지고 있다.

이를테면 getChild("body/table[4]/tr[0]/td[2]/table[1]/tr[8]/td[0]/img[0]") 는
body안에 5번째 table 태그안에 첫번째 tr안에 3번재 td안에 2번째 table안에 9번째 tr안에 첫번째 td안에 첫번째 img Tag를 가져오라는 뜻이다 -ㅅ-;;


만화그림 다운로드 받는데 쓰다가.
나중에 네이버나 다음에 있는 상장된 기업정보 페이지를 모두 긁어서 데이타베이스 구축하는데도 사용했다.


야후는 일정시간에 많은 GET이 날라가면 자동으로 해당 아이피 Block을 시켜버린다=ㅅ=
외국 기업이라 그런지 그런 기본적인 것에 충실하다.



'Framework > 아키텍쳐 일반' 카테고리의 다른 글

Class Design  (0) 2009.03.07
나쁜 디자인의 징후  (0) 2009.02.22
Design Principle - SRP  (0) 2009.02.22
Method Design  (0) 2009.02.11
몇가지 프로그래밍 조언  (0) 2009.02.10
Posted by bleujin