Playwrightでセッションを再利用する
PlaywrightでCookieやLocal storageをstate.jsonに保存してセッションを再利用する方法について紹介する。
次のようなコマンドを入力して実行し終了すると、CookieやLocal storageをstate.jsonに保存してくれる
playwright --save-storage=auth.json
例えば、次のようなコマンドで目的のサイトを開いてログインしてからブラウザを閉じる
npx playwright open "https://..." --save-storage=auth.json
コマンドから再利用する場合は次のようにする。
npx playwright --load-storage=auth.json
コードから再利用する場合は次のようにする。
import { test } from "@playwright/test";
test.use({
storageState: "auth.json",
});
test("auth", async ({ page }) => {
await page.goto("https://...");
//...
});