LoginSignup
1
1

More than 1 year has passed since last update.

JavaScriptで要素の出現を監視する

Last updated at Posted at 2021-12-18

php-webdriverなどのuntil + WebDriverExpectedConditionで要素の出現をチェックするみたいな動きをJSで力技でテスト的に実装してみました。

準備する

const scraping = {
  /** ================================================ **/
  // 対象要素の出力を待つ
  /** ================================================ **/
  waitingForTheElement: function (targetElement, waitingTime = 30) {
    return new Promise(function (resolve, reject) {
      let timer,timeout;

      // タイムアウトを設定(デフォルト: 30秒、この時間までに要素出力を確認できなければエラー扱いになる)
      timeout = setTimeout(function () {
        clearInterval(timer);
        reject(new Error(targetElement + " の取得に失敗しました。"));
      }, waitingTime * 1000);

      // 250ミリ秒毎にチェックを実行
      timer = setInterval(function () {
        if (document.querySelectorAll(targetElement).length > 0) {
          clearInterval(timer);
          clearTimeout(timeout);
          resolve();
        }
      }, 250);
    });
  }
}

document.querySelectorAll(targetElement).length > 0 この条件式を変更すれば好きな形式でのチェックを行うことができます。

使う

(async function () {
  console.log("実行します。");

  try {
    // #hoge という要素の出力を 最大10秒間 待機する
    await scraping.waitingForTheElement('#hoge', 10);
  } catch (e) {
    // タイムアウトしたときの処理
    console.log(e);
  }

  // 上の処理が完了したら下の処理が開始される。
  console.log("処理が完了しました。");
})();

2021/12/20 追記

MutationObserver は未知の要素に対する監視と、対象要素を子要素レベルまで絞り込めないだろうという妄想のもと使いませんでした。もし使えるなら多分そっちの方がいいですね、ごめんなさい。

それと、こっちの方が条件を自由に好きなように変えれるのでChrome拡張機能でのスクレイピングという意味では都合がいいんじゃないかなと思っています。

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