1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.js でスクレイピングのメモ(jsdom)

Last updated at Posted at 2023-11-12

Node.js の jsdom 使ってWebスクレイピングをやってみる
使ってる環境はこんな感じ

  • Windows11
  • node v18.17.1
  • jsdom v22.1.0

適当なフォルダ作成・移動

mkdir scraping
cd scraping

npm の初期化

npm init -y

jsdom インストール

npm i jsdom   

ES Modules 有効化

package.json に "type": "module" を追加

package.json
{
  "name": "scraping",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jsdom": "^22.1.0"
-  }
+  },
+  "type": "module"
}

スクレイピングするサンプルコード

適当なサイトをスクレイピングするサンプルコードです
Yahooニュース https://news.yahoo.co.jp/ の aタグ に設定してあるリンクを取得します

index.js
import jsdom from 'jsdom';
const { JSDOM } = jsdom;

const url = 'https://news.yahoo.co.jp/';
const exec = async () => {
  const dom = new JSDOM(await (await fetch(url)).text());
  dom.window.document
    .querySelectorAll('section a')
    .forEach((a) => console.log(a.href));
};

console.log('start');
exec();

実行と結果はこんな感じ...

実行
node index.js
結果
start
https://news.yahoo.co.jp/pickup/6481508
https://news.yahoo.co.jp/pickup/6481507
https://news.yahoo.co.jp/pickup/6481498
https://news.yahoo.co.jp/pickup/6481510



1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?