[Python] playwright python how to detect browser window is closed

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a simple Python script using requests.get to scrape data from a website that requires login. The script first checks whether the user is already logged in. If not, it launches a Chromium browser via Playwright and lets the user log in manually. After that, cookies are extracted from the Playwright context and passed to requests.get to continue the scraping.

    The behavior I want is: once the Playwright browser window is opened, the script should pause and wait until the user closes the window by clicking the "X" button in the top-right corner of the window. Once the window is closed, the script should resume execution.

    The problem is, I can't figure out how to properly detect when the user closes the browser window. I tried using page.is_closed() and browser.is_connected(), but neither of them worked as expected — they don't seem to detect when the window is closed manually. It looks like those checks only reflect the internal process, not the window state.

    Here’s a simplified version of my code:

    import time
    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("https://example.com/login")
    print("Please log in, then close the window")

    # Try to detect when the window is closed
    while True:
    if page.is_closed():
    print("Window is closed")
    break
    time.sleep(1)

    # Extract cookies
    cookies = context.cookies()
    print("Cookies:", cookies)

    browser.close()


    The while loop never exits, even if the user manually closes the browser window.

    Continue reading...

Compartilhe esta Página