playwright获取并复用登录信息

playwright获取并复用登录信息

  在Playwright中,可以使用browserContext.storageState()方法来获取当前浏览器上下文的存储状态,包括 cookies、localStorage 和 sessionStorage。你可以将这个存储状态保存下来,以便在下一次启动浏览器时恢复登录状态。

获取登陆信息

from playwright.sync_api import sync_playwright


with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()

    page.goto('you url')
    # 你的登陆操作
    # page.fill('id=userName', '*******')
    # page.fill('id=password', '*******')
    # page.click('xpath=//button[contains(@ta-name,"login-button")]')
    
    page.wait_for_load_state('networkidle')
    
    # storage_state = context.storage_state()
    storage = context.storage_state(path='cookie.json')
    print(storage)
    context.close()
    browser.close()

复用登陆信息

from playwright.sync_api import sync_playwright
import time

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    context = browser.new_context(storage_state='cookie.json')
    page = context.new_page()
    page.goto('you url')

    page.wait_for_load_state('networkidle')
    time.sleep(3)
    browser.close()
    

你可能感兴趣的:(python)