기본 콘텐츠로 건너뛰기

spiderable package를 살펴보았다.

동적페이지를 만들면 웹크롤러들이 찌르러 왔다가 빈손으로 돌아가곤 한다.
이래서야 안될일.

발번역부터 시작해보자.
// list of bot user agents that we want to serve statically, but do
// not obey the _escaped_fragment_ protocol. The page is served
// statically to any client whos user agent matches any of these
// regexps. Users may modify this array.
//
// An original goal with the spiderable package was to avoid doing
// user-agent based tests. But the reality is not enough bots support
// the _escaped_fragment_ protocol, so we need to hardcode a list
// here. I shed a silent tear.
우리가 정적으로 제공하고 싶지만 _escaped_fragment_ 프로토콜을 따르지 않는 봇 사용자 에이전트의 목록입니다.
페이지는 사용자 에이전트가 이러한 정규식 중 하나와 일치하는 모든 클라이언트에 정적으로 제공합니다. 사용자는 이 배열을 변경할 수 있습니다.
spiderable 패키지와 원래 목표는 사용자 에이전트 기반의 테스트를 실시하는 것을 피하기 위해서였다.
하지만 현실은 봇들은 _escaped_fragment_ 프로토콜을 지원하지 않기 때문에, 여기에서는 목록을 하드 코딩해야합니다. 나는 조용히 눈물을 흘렸다.
Spiderable.userAgentRegExps = [
    /^facebookexternalhit/i, /^linkedinbot/i, /^twitterbot/i];

요놈들! 말을 듣지 않는 나쁜 아이들이 니 놈들이렸다! 이 오라질 것들!
아래와 같이 javascript 코드를 생성하여 phantom.js에 밀어 넣는다. 파일로에서 넣지 않고 바로 생성하기 위해 /dev/stdin 을 사용하여 밀어넣는다. 아마 이것 때문에 윈도우에선 애로사항이 꽃필 것이다. 방법이야 있지만 패스.

    var phantomScript = "var url = " + JSON.stringify(url) + ";" +
          "var page = require('webpage').create();" +
          "page.open(url);" +
          "setInterval(function() {" +
          "  var ready = page.evaluate(function () {" +
          "    if (typeof Meteor !== 'undefined' " +
          "        && typeof(Meteor.status) !== 'undefined' " +
          "        && Meteor.status().connected) {" +
          "      Deps.flush();" +
          "      return DDP._allSubscriptionsReady();" +
          "    }" +
          "    return false;" +
          "  });" +
          "  if (ready) {" +
          "    var out = page.content;" +
          "    out = out.replace(/<script[^>]+>(.|\\n|\\r)*?<\\/script\\s*>/ig, '');" +
          "    out = out.replace('<meta name=\"fragment\" content=\"!\">', '');" +
          "    console.log(out);" +
          "    phantom.exit();" +
          "  }" +
          "}, 100);\n";

소스 코드의 주 내용은 별게 없다. url을 인자로 받은 페이지를 만들어 반환하되 페이지 렌더링이 끝나는 시간을 가정하여 0.1초마다 계속 Meteor 어플리케이션의 존재를 확인하면 Deps를 flush하고 모든 subscription 들을 완료하였는지를 ready로 넘겨준다. 마지막으로 ready가 참이면 page.content를 넘겨주면서 끝난다.

단, <script>덩어리들을 홀랑 날리고 <meta name="fragment" content="!"> 도 홀랑홀랑 날린 다음에 stdout으로 보내주는 것이다. 평범한 html 문서 조각이 되는 것이다.

자. 큰덩어리로 돌아가는 구조를 말로 한번 풀어보자면 이런 것이다.

WebApp.connectHandlers 를 통해 들어온 놈들 중
request url이 _escaped_fragment_= 를 포함하거나  user-agent 이름이 facebookexternalhit, linkedinbot, twitterbot 같은 걸로 들어올 때
phantomJS를 가동해서 page.content를 얻은 다음 페이지로딩이 완료된 다음에 <script>와 <meta name="fragment" content="!"> 을 제거해서 돌려준다...
google 같은 경우 <meta name="fragment" content="!">가 있는 경우 _escaped_fragment_=를 붙여서 요청하는데 이때 phantomJS로 렌더링한 페이지 본문을 넘겨준다.

...라는 아름다운 이야기가 되겠다.

이래도 뭔소린지 모르겠다면 진리의 evetedmind 동영상을 보자.
https://www.eventedmind.com/posts/meteor-the-spiderable-package

재밌는 건 이 링크도 역시 spiderable 적용이다.
curl https://www.eventedmind.com/posts/meteor-the-spiderable-package
한 결과랑

curl https://www.eventedmind.com/posts/meteor-the-spiderable-package?_escaped_fragment_=
한 결과를 비교해보면 한눈에 알 수 있다.

마찬가지로 다른 bot들을 적용해보려면 user-agent를 주면 된다.

curl -s -A "facebookexternalhit" https://www.eventedmind.com/posts/meteor-the-spiderable-package

훌륭하지 않은가?

댓글

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

OS X 터미널에서 tmux 사용시 pane 크기 조절

http://superuser.com/a/660072  글 참조. OS X 에서 tmux 사용시 나눠놓은 pane 크기 조정할 때 원래는 ctrl+b, ctrl+↑←→↓ 로 사이즈를 조정하는데 기본 터미널 키 입력이 조금 문제가 있다. 키 매핑을 다시 하자 Preferences(cmd+,) > Profile >  변경하고자 하는 Theme 선택 > Keyboards 로 들어가서 \033[1;5A \033[1;5B \033[1;5C \033[1;5D 를 순서대로 ↑↓→←순으로 매핑이 되도록 하면 된다. +를 누르고 Key에 해당 화살표키와 Modifier에 ctrl 선택 한 후 <esc>, [, 1, ;, 5 까지 한키 한키 입력 후 A,B,C,D를 써준다. 잘못 입력했을 땐 당황하지 말고 Delete on character 버튼을 눌러 수정하도록 하자. 그리고 다시 tmux에서 ctrl+b, ctrl+↑←→↓로 사이즈를 조절해보자. 잘 된다.