Cheerioを使用してWebスクレイピング

Cheerioを使用してWebスクレイピング

2023/05/13

2024/05/12

npmパッケージ「Cheerio」を使用してWebスクレイピングを行う方法です。
このサイトtukkyteck.comを対象として操作してみます。

前提条件

・node.jsがインストールされていること

npm install

任意のフォルダを作成し、cheerioとWebサイトのhtml情報を取得するためにaxiosをインストールします。

npm install cheerio
npm install axios


記事取得

index.jsに以下のように記述します。
GitHubにソースあります。
index.js

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

const fetchData = async () => {
  const URL = "https://tukkytech.com/";
  const result = await axios(URL);
  const htmlParser = result.data;
  const $ = cheerio.load(htmlParser);

  // id="articles"の中のliタグを取得し、その中のh5タグとaタグのテキストを取得して出力する処理を繰り返す
  $("#articles")
    .find("li")
    .each(function (i) {
      const title = $(this).find("h5").text();
      const url = $(this).find("a").attr("href");

      console.log(`${title}\nhttps://tukkytech/${url}\n`);
    });
};

fetchData();


出力結果

Cheerioを使用してWebスクレイピング
https://tukkytech.com/blog/nodejs-cheerio/

ACMにドメインを設定する
https://tukkytech.com/blog/aws-acm/

Next.js × microCMSで記事を全件取得する
https://tukkytech.com/blog/microcms-all-articles/

VSCodeにPrettierを設定する
https://tukkytech.com/blog/prettier-setting/

TypeScriptの学習に使用したいサイト
https://tukkytech.com/blog/typescript-learning/

~省略


要素の取得方法の例

$(selector)
指定されたCSSセレクターに一致する最初の要素を返します。

$(selector, context)
指定されたCSSセレクターに一致する最初の要素を、指定されたコンテキスト内から検索して返します。

$(selector, element)
指定されたCSSセレクターに一致する最初の要素を、指定された要素内から検索して返します。

$(element)
指定されたHTML要素をCheerioオブジェクトに変換します。

$(html)
指定されたHTML文字列をCheerioオブジェクトに変換します。

$(selector).attr(attributeName)
指定された属性名の値を取得します。

$(selector).text()
指定された要素のテキストを取得します。

$(selector).each(function)
要素の集合を反復処理します。

$(selector).find(selector)
指定されたCSSセレクターに一致する要素を、指定された要素の子孫から検索して返します。

参考資料

Cheerio Tutorial