Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Playwright で HTML を直接書き換える例 ( DOM 操作 ) ( Evaluating JavaScript ) #3606

Open
YumaInaura opened this issue Apr 24, 2024 · 0 comments

Comments

@YumaInaura
Copy link
Owner

YumaInaura commented Apr 24, 2024

Playwrightのテストでどうしても直接DOM操作をする必要がある場合は、出来るようだ

テストファイルの例

test('example', async ({ page }) => {
  await page.goto('http://example.com')

  await page.screenshot({
    path: `before.png`,
  })

  await page.evaluate(() => {
    const h1Element = document.querySelector('h1')

    if (h1Element) {
      h1Element.innerHTML = 'Overwritten BY Playwright!'
    }
  })

  await page.screenshot({
    path: `after.png`,
  })
})

結果

書き換え前の画像

image

書き換え後の画像

image

公式説明

Playwright scripts run in your Playwright environment. Your page scripts run in the browser page environment. Those environments don't intersect, they are running in different virtual machines in different processes and even potentially on different computers.

The page.evaluate() API can run a JavaScript function in the context of the web page and bring results back to the Playwright environment. Browser globals like window and document can be used in evaluate.

Playwright スクリプトは Playwright 環境で実行されます。ページ スクリプトはブラウザ ページ環境で実行されます。これらの環境は交差せず、異なるプロセスの異なる仮想マシンで実行されており、場合によっては異なるコンピューター上でも実行されます。

page.evaluate() API は、Web ページのコンテキストで JavaScript 関数を実行し、結果を Playwright 環境に戻すことができます。ウィンドウやドキュメントなどのブラウザ グローバルは評価で使用できます。

https://playwright.dev/docs/evaluating

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

プロフィール・経歴

https://github.com/YumaInaura/YumaInaura

@YumaInaura YumaInaura changed the title Playwright で HTML を直接書き換える例 ( DOM 操作 ) Playwright で HTML を直接書き換える例 ( DOM 操作 ) ( Evaluating JavaScript ) Apr 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant