cheerio - Node.js

  • 作成日:
  • 最終更新日:2025/11/04

Cheerio とは?

Cheerioは、主にウェブスクレイピング(Web Scraping)やHTMLの解析・操作に使われるライブラリです。

npm install cheerio

HTML ファイルの取得と解析

axios を使ってHTMLファイルを取得し、cheerioを使って解析します。

HTMLファイル

<!DOCTYPE html>
<html>
  <head>
    <title>Express</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>Express</h1>
    <p>Welcome to Express</p>
    <div id="target">
      <h2>hello world</h2>
    </div>
    <ul>
      <li class="test">リスト1</li>
      <li class="test">リスト2</li>
      <li class="test">リスト3</li>
    </ul>
  </body>
</html>

axios.js

const axios = require('axios');
const cheerio = require('cheerio');

(async () => {
  try {
    // HTMLを取得
    const response = await axios.get('http://localhost:3000');

    // cheerioでHTMLを読み込む
    const $ = cheerio.load(response.data);

    // タイトル要素を取得
    const title = $('h1').text();  // h1タグの中のテキスト
    console.log('タイトル:', title);

    // 複数要素をループして取得
    $('p').each((i, elem) => {
      console.log('段落', i + 1, ':', $(elem).text());
    });

    const target = $('#target > h2').text();
    console.log(target);

    $('.test').each((i, elem) => {
      console.log('リスト', ':', $(elem).text());
    })

  } catch (error) {
    console.error('取得エラー:', error);
  }
})();

上記のJavascript のファイルを実行する前に、Express.jsのアプリを起動しておきます。

ローカル上のExpress.jsのアプリのindex.ejsファイルのデータを取得しています。

node axios.js

結果
-----------------------------------------
タイトル: Express
段落 1 : Welcome to Express
hello world
リスト : リスト1
リスト : リスト2
リスト : リスト3