본문 바로가기
배우고 있습니다/Node.js 개발

[Node.js 활용기] 웹크롤링(casperjs/PhantomJS ) for 반복문

by 유헤 2018. 12. 27.

안녕하세요. 유헤입니다.

오늘은 웹크롤링을 하면서 같은 구간을 반복하거나

같은 코드를 반복해야하는 경우 처리 방법에 대해 알려드리고자 합니다.




http://docs.casperjs.org/en/latest/modules/casper.html

를 참조해보면, repeat() 이라는 함수가 있습니다.


casper.start() 

casper.run()


사이에 반복되는 구간이 있을때 사용하시면 되며,


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var cnt=1
 casper.repeat(4, function() {
  casper.then(function(){
   var path= ".db_nationset_block > ul > li:nth-child("+cnt+") > a";
   cnt++;
   if(casper.exists(path)){
     casper.mouseEvent('click', path);
   }
   casper.wait(300);
 }).then( function(){
     //car 로 입력된 결과값 읽어오기
     for(var i=0; i<15; i++){
         var usReuslt = function(i){
         var a = document.querySelector(  ".toclist_tbtype > tbody tr:nth-child( "+ i +" ) "  ).innerText;
         return a;
     };
     var result = this.evaluate( usReuslt , i );
     //파일 저장/////
     savePath="/data/wipsplus/nodejs/crawling/a.txt";
     fs.write(savePath, result, 'w');
     console.log(cul+"검색결과 : "+  result );
    }
 });
});
 
 
 
cs


repeat 반복문 구간 안에 포함된 내용이 반복되서 실행된다.


repeat( 반복할 숫자, 실행  함수 )