[Python] How to subscribe to download events at the Browser or Context level in Playwright...

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

  1. Stack

    Stack Membro Participativo

    I'm using Playwright for Python and need to download files from CNKI. The challenge is that when I click a download icon/button, one of two things can happen:

    1. The download starts directly on the current page.
    2. A new popup page appears (asking for a CAPTCHA), and after interacting with this popup, the download is initiated from this new popup page.

    My current approach using page.expect_download() works if the download starts on the initial page, like this:

    # icon is a Playwright Locator for the download button
    with page.expect_download() as download_info:
    icon.click()
    download = download_info.value
    # Process download...


    However, this fails if a popup appears and the download originates from that new page, because page.expect_download() is tied to the original page object. The popup page might also close itself quickly after initiating the download.

    In addition, due to website restrictions, I can't initiate the download through page.goto("download_url").

    Maybe I need a way to listen for any download event that occurs within the Browser or BrowserContext, like context.expect_download(),regardless of which page (the original one or a subsequently opened popup) initiates it.

    I've looked into some Playwright GitHub issues which suggest that functionality for context-level download handling should exist or has been discussed, however, I haven't found clear examples or documentation about this:

    bug/Playwright popup page download
    Feature/Context level download events
    feat(downloads): subscribe to download events in Browser domain instead of Page

    I'm new to Playwright and have been stuck on this for a couple of days. Any working examples or pointers to the correct API usage would be greatly appreciated!

    Continue reading...

Compartilhe esta Página