상세 컨텐츠

본문 제목

[Phantomjs] Phantomjs를 이용해서 웹페이지 캡쳐하기 (3)

Javascript

by 메타샤워 2023. 7. 19. 15:45

본문

다음은 원하는 URL에 따라 웹페이지를 캡쳐하는 방식을 도전해볼 것이다.

이전에 작성했던 loadPage.js의 파일에 Argument를 추가해서 node에서 원하는 URL을 loadPage.js로 넘겨서 이미지파일을 받아낼것이다.
 
먼저 loadPage.js를 아래와 같이 수정하자
 
 
var page = require('webpage').create();
var system = require('system');
 
if ( system.args.length == 1){
    console.log('Usage : loadPage.js <someURL>');
    phantom.exit();
}
 
address = system.args[1];
page.open(address, function (status){
    if (status != 'success'){
        console.log ('FAIL to load the address');
    } else {
        page.render('./tmp/image.jpg');
    }
 
    phantom.exit();
});

 

system 모듈을 이용해서 loadPage.js가 실행될때 System Argument를 찾아내 그 Argument로 넘어온 URL을 찾을 예정이다.
다음은 main.js의 파일을 아래와 같이 수정하자
var childProcess = require('child_process');
var phantomjs = require('phantomjs');
var binPath = phantomjs.path;
var path = require('path');
 
var url = 'http://www.whateverYouWant.com';
var childArgs = [
    path.join(__dirname, 'loadPage.js'),
    url  // <- 실행시킬 URL을 childProcess의 두번째 Argument로 넘긴다.
];
 
childProcess.execFile(binPath, childArgs, function (err,stdout, stderr){
    console.log('good');
});

이상 node.js에서 phantomjs 사용하기 기초 끝 

관련글 더보기