LoginSignup
5
5

More than 5 years have passed since last update.

nodejsにてHTMLを解析したい場合使うべきLibとは?

Posted at

突然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を使うことになりました。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5