[Python] Playwright Python: Session Cookies Not Persisting in `launch_persistent_context` -...

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Playwright for Python with launch_persistent_context to create a persistent browser context that should retain cookies across browser launches. However, I've noticed that session cookies (those without an Expires or Max-Age attribute) do not persist when relaunching the context, while cookies with an explicit Expires attribute do persist. Is this expected behavior, or is it a bug in Playwright?

    Code Example


    Below is a simplified test script that demonstrates the issue:

    import os
    import shutil
    from datetime import datetime, timedelta

    from playwright.sync_api import sync_playwright


    def test_persistent_cookies():
    user_data_dir = './user_data'
    if os.path.exists(user_data_dir):
    shutil.rmtree(user_data_dir)

    with sync_playwright() as p:
    # First launch: Set a session cookie and a non-session cookie
    context = p.chromium.launch_persistent_context(
    user_data_dir, headless=True
    )
    page = context.new_page()
    page.goto('https://example.com')

    # Session cookie (no expires)
    session_cookie = {
    'name': 'session_cookie',
    'value': 'session_value_123',
    'domain': 'example.com',
    'path': '/',
    'httpOnly': False,
    'secure': False,
    'sameSite': 'Lax',
    }

    # Non-session cookie (with expires)
    future_time = int((datetime.now() + timedelta(days=1)).timestamp())
    persistent_cookie = {
    'name': 'persistent_cookie',
    'value': 'persistent_value_456',
    'domain': 'example.com',
    'path': '/',
    'expires': future_time,
    'httpOnly': False,
    'secure': False,
    'sameSite': 'Lax',
    }

    context.add_cookies([session_cookie, persistent_cookie])

    # Verify cookies in first session
    cookies = context.cookies()
    cookie_names = [cookie['name'] for cookie in cookies]
    print('First session cookies:', cookie_names)

    assert 'session_cookie' in cookie_names, 'Session cookie not set'
    assert 'persistent_cookie' in cookie_names, 'Persistent cookie not set'

    context.close()

    # Second launch: Check cookie persistence
    context2 = p.chromium.launch_persistent_context(
    user_data_dir, headless=True
    )
    cookies = context2.cookies()
    cookie_names = [cookie['name'] for cookie in cookies]
    print('Second session cookies:', cookie_names)

    if 'session_cookie' not in cookie_names:
    print('BUG: Session cookie did not persist in second session')

    assert 'persistent_cookie' in cookie_names, (
    'Persistent cookie did not persist'
    )

    context2.close()
    shutil.rmtree(user_data_dir)


    if __name__ == '__main__':
    test_persistent_cookies()

    Observed Behavior


    $ .../.venv/Scripts/python.exe .../~scratch.py
    First session cookies: ['session_cookie', 'persistent_cookie']
    Second session cookies: ['persistent_cookie']
    BUG: Session cookie did not persist in second session
    Test completed!


    The session cookie (session_cookie) is present in the first session but missing in the second session. The non-session cookie (persistent_cookie) persists correctly across both sessions.

    Expected Behavior


    Since launch_persistent_context uses a user data directory to store browser data, I expect both session and non-session cookies to persist across browser launches, as the user data directory should retain all cookies set in the context.

    Environment

    • Playwright Version: 1.52.0
    • Python Version: 3.13.3
    • Operating System: Windows (both 10 and 11)
    • Browser: Chromium (headless or non-headless)
    Additional Context


    The script uses context.add_cookies() to set cookies, but I get the same result when cookies are set via a page interaction (e.g., JavaScript).

    I’ve ensured the user data directory is clean before each run to avoid interference.

    The Playwright documentation doesn’t explicitly state whether session cookies should persist in a persistent context, but the mention of "browser session data like cookies" suggests they should.

    I’m aware that using context.storage_state() can persist session cookies by saving and loading the state, but I prefer launch_persistent_context because it retains cached content like JavaScript and CSS files, avoiding redownloads and improving performance.

    Any insights into whether this is intended behavior or a bug, and potential workarounds, would be greatly appreciated! Should I file a bug report with the Playwright team?

    Continue reading...

Compartilhe esta Página