LoginSignup
15
12

More than 3 years have passed since last update.

【TypeScript】Webスクレイピングのやり方

Last updated at Posted at 2019-09-19

関連

準備

今回使用するモジュールはこちら

  • request, request-promise-native, @types/request-promise-native
    HTTPリクエスト送信
    (2020/06/22 追記)こちらのライブラリは既に deprecated になっているので、他の代替ライブラリの仕様を検討してください。代替ライブラリの例としては「Alternative libraries to request · Issue #3143 · request/request」をご参照ください。

  • chardet, @types/chardet

    文字コード判定

  • iconv-lite

    文字コード変換

  • jsdom, @types/jsdom

    HTMLパーサ

$ npm i request request-promise-native @types/request-promise-native chardet @types/chardet iconv-lite jsdom @types/jsdom

サンプルコード

import * as request from 'request-promise-native';
import * as chardet from 'chardet';
import * as iconv   from 'iconv-lite';
import { JSDOM }    from 'jsdom';

const main = async () => {
  const url = 'スクレイピングしたいページのURL';

  // HTTPリクエスト送信
  const option = {
    url: url,
    encoding: null
  };
  const response = await request.get(option);

  // 文字コード判別
  const encoding = chardet.detect(response)!.toString();
  if(!encoding) throw new Error();

  // 文字コード変換
  const html: string = iconv.decode(response, encoding);

  // HTMLパース
  const jsdom = new JSDOM(html);
  const document = jsdom.window.document;

  // スクレイピング
  // ここからはquerySelectorとかgetElementByIdとかお馴染みのメソッドで好きなだけスクレイピングしちゃってください
  const elm = document.querySelector('hogehoge');

  // ...
};
main();

参考

15
12
2

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
15
12