突然nodejsにてHTMLを解析の仕事が出てきた。
調べた結果、jquery
(ウェブ側のjQueryとちょっと違う)とcheerio
を洗い出した。
1. jquery
HOME: https://github.com/UncoolAJ86/node-jquery
インストールはコマンド2個:
npm install -S 'jquery@>=2.1'
npm install -S 'jsdom@latest'
ですが、jsdom
のインストールは遅い!
> contextify@0.1.8 install /Users/liubin/github/ss4cn/node_modules/jsdom/node_modules/contextify
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz
CXX(target) Release/obj.target/contextify/src/contextify.o
SOLINK_MODULE(target) Release/contextify.node
SOLINK_MODULE(target) Release/contextify.node: Finished
jsdom@0.10.6 node_modules/jsdom
nodejs
自体のダウンロードとビルドが必要です。
使う方法も面倒くさい。具体的に本家のサンプルをご参照。
ドキュメントは不備。
2 cheerio
HOME: http://matthewmueller.github.io/cheerio/
インストールは簡単かつ迅速
npm install cheerio
詳しいドキュメントが用意されている。使うも簡単。
// from https://github.com/cheeriojs/cheerio
var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html();
//=> <h2 class="title welcome">Hello there!</h2>
欠点:httpから直接HTMLコンテントを取得するメソッドが無い。request
パッケージを使うと自前実装しなければならない。
3 結局
cheerio
を使うことになりました。