The strongest automated testing framework Playwright (7) - use cookies to avoid repeated logins

playwright executes tests in an isolated environment called a browser context . This isolation model improves repeatability and prevents cascading test failures. Tests can load existing authenticated state. This removes the need to authenticate on every test and speeds up test execution.

Login before each test

The following example logs into GitHub. After performing these steps, the browser context is authenticated.

  • Synchronize
page = context.new_page()
page.goto('https://github.com/login')

# Interact with login form
page.get_by_label("Username or email address").fill("username")
page.get_by_label("Password").fill("password")
page.get_by_role("button", name="Sign in").click()
# Continue with the test

Redoing the login for each test can slow down test execution. To alleviate this problem, existing authentication states can be reused.

Reuse logged in state

Web applications use cookie-based or token-based authentication, where the authenticated state is stored as a  cookie  or in local storage .

 

Use localStorage in the console to print out cookies.

 

Playwright provides  the browserContext.storageState([options])  method to save the cookie to a local file.

context = browser.new_context(storage_state="state.json")

Example:

Save the cookie to the state.json file

from playwright.sync_api import Playwright, expect


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://pity.fun/#/user/login")
    page.get_by_placeholder("用户名: tester").click()
    page.get_by_placeholder("用户名: tester").fill("tester")
    page.get_by_placeholder("密码: tester").fill("tester")
    page.get_by_role("button", name="登 录").click()
    expect(page.get_by_title("工作台")).to_be_visible()

    # 保存storage state 到指定的文件
    storage = context.storage_state(path="state.json")

    # ---------------------
    context.close()
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

 

Get cookie from state.json, use that cookie for login when creating context


from playwright.sync_api import Playwright, sync_playwright


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    # 加载本地cookies,免登陆
    context = browser.new_context(storage_state="state.json")

    # 打开页面继续操作
    page = context.new_page()
    page.goto('https://pity.fun')
    page.pause()  # 打断点看是不是已经登录了

    context.close()
    browser.close()

with sync_playwright() as playwright:
    run(playwright)
After execution, you can see that after opening the browser, you have logged in.

Advanced plan

session storage

Reusing authenticated state includes  cookies  and local storage based authentication. Session storage is rarely used to store information associated with login state. Session storage is specific to a particular domain and is not persisted across page loads. Playwright does not provide an API for persisting session storage, but the following code snippets can be used to save/load session storage.

import os
# Get session storage and store as env variable
session_storage = page.evaluate("() => JSON.stringify(sessionStorage)")
os.environ["SESSION_STORAGE"] = session_storage

# Set session storage in a new context
session_storage = os.environ["SESSION_STORAGE"]
context.add_init_script("""(storage => {
  if (window.location.hostname === 'example.com') {
    const entries = JSON.parse(storage)
    for (const [key, value] of Object.entries(entries)) {
      window.sessionStorage.setItem(key, value)
    }
  }
})('""" + session_storage + "')")

Guess you like

Origin blog.csdn.net/seanyang_/article/details/132248176