初心者向け jsdom の使い方について - Node.js

jsdom

jsdom をインストールするには、以下のようにします。

npm i jsdom

文字列の HTML をスクレイピングするには、以下のようにします。

const { JSDOM } = require('jsdom');

const body = `<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>タイトル</title>
</head>
<body>
<img id="hoge" src="sample1.jpg" alt="">
<img src="img.png">
</body>
</html>`

const dom = new JSDOM(body);
dom.window.document.querySelectorAll("img").forEach((a) => {
  console.log(a.src)
})

node-html-parser

node-html-parser のインストールするには、以下のようにします。

npm i node-html-parser

文字列の HTML をスクレイピングするには、以下のようにします。

var HTMLParser = require('node-html-parser');

const body = `<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>認証した場合のみ画像表示</title>
</head>
<body>
<img id="hoge" src="before_sample.jpg" alt="">
<img src="img.png">
</body>
</html>`

const dom = HTMLParser.parse(body);
dom.querySelectorAll("img").forEach((a) => {
  a.setAttribute('src', 'after_sample.png')
})

// 変更後のHTMLを取得
console.log(dom.toString())