Search code examples
pythonautomationdownloadplaywrightplaywright-python

Download files with goto in playwright-python


Is there a way to download a file by going straight to its download link with goto in playwright-python?

async with page.expect_download(timeout=420000) as download_info:
        await page.goto(f'https://example.com/gateway/reports/{id}/file')

Download = await download_info.value
await Download.save_as(Download.suggested_filename)

Solution

  • The only way I found is wrap the goto inside a try-except block

    Content of main.py

    from playwright.sync_api import Playwright, sync_playwright, expect
    
    with sync_playwright() as p:
        #We define the browser, the context and the page
        browser = p.chromium.launch(headless=False)
        context = browser.new_context()
        page = browser.new_page()
        with page.expect_download() as download_info:
            #If we navigate without try, it will throw an exception and it will stop our script, so, we wrap it inside a try except block
            try:
                page.goto("https://manueltgomes.com/wp-content/uploads/2021/09/ParseHTMLLInks_1_0_0_1.zip")
            except:
                pass
        download = download_info.value
        download.save_as(f"./{download.suggested_filename}")
        context.close()
        browser.close()
    

    Then just run python3 main.py

    The file will be saved in the same path of the main.py file