0

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)
Py Ton
  • 23
  • 1
  • 7

1 Answers1

3

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

Jaky Ruby
  • 1,409
  • 1
  • 7
  • 12
  • similar situation in javascript/typescript, need to surround the goto with a try catch, see https://stackoverflow.com/questions/73365450/unable-to-download-with-playwright-headless-true-from-url-link/75890678#75890678 for more details – Jeff Richards Mar 30 '23 at 16:21