Playwright その他の操作

Playwrightで表示中の画面のスクリーンショットをとる

Playwrightで表示している画面のスクリーンショットを取得する方法です。

page.screenshot()メソッドを使用します。引数に保存するファイル名を指定します。
・表示している画面だけでなくてページ全体のスクリーンショットを取得したい場合は、fullPageオプションを指定します。
・要素を指定してscreenshot()メソッドを使用すれば、その要素のスクリーンショットが取得されます。
・ファイルパスを指定しなければscreenshot()の戻り値でスクリーンショットしたデータのバッファが取得できます。

サンプル

						await page.goto('https://web.biz-prog.net/test/testpage.html');

						//表示中の画面のスクリーンショットをとる
						await page.screenshot({ path: 'test.png' });
					  
						//表示中の画面の全体のスクリーンショットをとる
						await page.screenshot({ path: 'test-all.png', fullPage: true });
					  
						//要素を指定してスクリーンショットをとる
						await page.getByRole("heading", { name: "Web操作テストページ" }).first().screenshot({ path: 'test-header.png' });
					  
						//バッファにスクリーンショットのデータをとる
						const buffer = await page.getByRole("heading", { name: "Web操作テストページ" }).first().screenshot();
						console.log(buffer.toString('base64'));
					

					

						
					

参考