LoginSignup
0
0

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

Posted at

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 環境に戻すことができます。ウィンドウやドキュメントなどのブラウザ グローバルは評価で使用できます。

チャットメンバー募集

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

プロフィール・経歴

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