티스토리 뷰

phantomjs, casperjs를 이용해 facebook login해서 크롤링 하기



phantomjs(팬텀js)란?

handless(핸들리스) 웹브라우저로서 커맨드라인(소스코드)으로 웹브라우저를 실행 시켜서 특정 값을 뽑아내거나 비교할 때 사용한다.

웹 브라우져는 로그인이나 특정 값들을 넣을 때 마우스로 클릭 하거나 탭으로 이동하고 해당 값들을 키보드나 마우스로 넣어주어야 한다.

하지만 데이터를 가지고 오거나 값을 비교하거나 web app을 테스트 할 때는 해당 과정이 반복되어 매번 넣어주기가 어렵기 때문에

이걸 사용한다.


casperjs란?

팬텀 js를 조금 더 세밀하게 컨트롤 할 수 있는 기능들을 묶어놓은 라이브러리이다.



로그인한 페이지를 크롤링 하고 싶을 때 사용하는 방법입니다.

아래 your_id, your_password에 개인 id와 pw를 넣고 사용하시기 바랍니다.


npm을 이용한 라이브러리 설치


npm init

npm install --save casperjs phantomjs



main.js

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
phantom.casperPath = './node_modules/casperjs';
phantom.injectJs('./node_modules/casperjs/bin/bootstrap.js');
 
var fs = require('fs')
 
var casper = require('casper').create({
    pageSettings: {
        loadImages: false,//The script is much faster when this field is set to false
        loadPlugins: false,
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
    }
});
 
//open Facebook
casper.start().thenOpen("https://facebook.com"function() {
    console.log("Facebook website opened");
});
 
//로그인
casper.then(function(){
    console.log("해당 id와 pw로 로그인 합니다.");
    this.evaluate(function(){
        document.getElementById("email").value="your_id";
            document.getElementById("pass").value="your_password";
            document.getElementById("loginbutton").children[0].click();
    });
});
 
//스크린샷 찍고 페이지 저장하기
casper.then(function(){
    console.log("6초 후에 AfterLogin.png 으로 저장됩니다.");
    this.wait(6000function(){
      // After 6 seconds, this callback will be called, and then we will capture:
      this.capture('AfterLogin.png');
      fs.write("./hello.html", this.getHTML(), "w")
    });
});
 
//이미지 주소 받아오기
casper.then(function(){
    var images = this.evaluate(function(){
        var facebookImages = document.getElementsByTagName('img');
        var allSrc = [];
        for(var i = 0; i < facebookImages.length; i++) {
            if(facebookImages[i].height >= 100 && facebookImages[i].width >= 100)
                allSrc.push(facebookImages[i].src);
        }
        return JSON.stringify(allSrc);
    });
    console.log(images);
})
 
casper.run();
 
cs


실행하기

phantomjs main.js



end.



공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
28 29 30
글 보관함