1. 동적 웹컨텐츠
아래와 같이 파이어폭스의 개발자 도구의 "네트워크" 텝을 켜서 보면, 응답의 형식이 html이 아닌, json 이나 xml 인 경우가 있다. 브라우저가 이러한 응답을 읽어서 내용을 표시해주는데 보통의 ajax 방식으로 로딩되는 경우가 이러한 경우이다. 이런 경우는 소스에서 Request 을 하는 url 을 찾기 쉽지 않다. 그래서 PhantomJS 와 같은 브라우저를 이용해서 웹페이지를 로컬로 임시로 저장해서 그것을 크롤링 하는 방법을 사용해보기로 한다. 더 좋은 방법이 있을법도 한데, 일단 동작하는 프로그램을 빨리 만들어보자.
2. PhantomJS
맥에서 PhantomJS을 사용하려면 소스코드를 다운받고 빌드를 해주어야 한다. 아래 문서를 참고하자. http://phantomjs.org/build.html
git submodule update 까지 해주고 실행하고 build을 하려고 하면 OpenSSD, Xcode 등이 없다고 빌드가 되지 않는다. 다 설치해주고 나서 build 을 해주자. build 는 조금 시간이 걸린다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var page = require('webpage').create(); | |
var system = require('system'); | |
var fs = require('fs'); | |
if (system.args.length === 1) { | |
console.log('Usage: loadspeed.js <some URL>'); | |
phantom.exit(); | |
} | |
var address = system.args[1]; | |
page.open(address, function(status) { | |
if (status) { | |
fs.write('test.html', page.content, 'w'); | |
} | |
phantom.exit(); | |
}); |
그리고 나서 phantomjs을 이용해서 웹페이지를 로컬로 저장해보자. 간단한 js 스크립트를 이용해서 저장을 한다. 위의 소스코드는 "http://yujuwon.tistory.com/entry/PhantomJS-사용하기" 에서 복사해온 것이다. 그리고 나서 아래처럼 실행해보자.
➜ phantomjs git:(d9cda3d) ✗ ./bin/phantomjs save_web.js http://sports.news.naver.com/wfootball/news/index.nhn
공식문서의 아래 문서를 참조하면 도움이 된다.
http://phantomjs.org/screen-capture.html
3. 크롤링 라이브러리
크롤링 하는 프로그램은 scrapy 라는 파이썬 라이브러리를 이용해서 작성하고 있다. 여러모로 편리하다.http://scrapy.org