0
0

More than 1 year has passed since last update.

puppeteerでshadowRoot内の要素を取得する

Last updated at Posted at 2022-04-23

背景

Wordleのスクレイピングしようとしたが、ゲーム説明モーダルの閉じるボタンをpuppeteerでクリックする際にちょっとつまづいたので備忘録を残しておく。
image.png

結論

puppeteerのpage.evaluateを使用しshadowRoot以下を取得するようなJSを実行する。

  await wordlePage.evaluate(() => {
    const closeModalIcon = document.querySelector("body > game-app")?.shadowRoot?.querySelector("#game > game-modal")?.shadowRoot?.querySelector<HTMLElement>("div > div > div")
    closeModalIcon?.click()
  })

おわり

ひねりもなく素直にやっただけだが、shadowRootを取得するようなpuppeteerのメソッドを探して変に時間がかかってしまった...
page.evaluateで素直にJSを実行できるので困ったらこれを使えば大体解決しそう。

おまけ

ブラウザの開発者ツール(下の画像はOpera)からある要素に対するセレクタとかJSパスをコピーすることができるのでスクレイピングする際にかなり重宝する。
image.png

参考

https://zenn.dev/atom/articles/750f9660f6a70a
https://github.com/puppeteer/puppeteer/issues/858#issuecomment-359750382
https://developer.mozilla.org/ja/docs/Web/API/Element/shadowRoot

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