3

I'm trying to download a file from a website using Playwright. The button that triggers the download does some js and then the download starts.

Clicking the button using the .click function triggers a download but it shows an error: Failed - Download error.

enter image description here

I've tried using the devtools protocol Page.setDownloadBehavior, but this doesn't seem to do anything.

    const playwright = require("playwright");
    const { /*chromium,*/ devices } = require("playwright");
    const iPhone = devices["iPad (gen 7) landscape"];

    (async () => {
        const my_chromium = playwright["chromium"];
        const browser = await my_chromium.launch({ headless: false });
        const context = await browser.newContext({
            viewport: iPhone.viewport,
            userAgent: iPhone.userAgent
        });
        const page = await context.newPage();
        const client = await browser.pageTarget(page).createCDPSession();
        console.log(client);
        await client.send("Page.setDownloadBehavior", {
            behavior: "allow",
            downloadPath: "C:/in"
        });
        //...and so on
        await page.click("#download-button");
        browser.close();
    })();

Full file here

There is a proposal for a better download api in Playwright, but I can't find the current API. There was a suggestion that something to do with the downloadWillBegin event would be useful, but I've no idea how to access that from Playwright.

I'm open to the suggestion that I should use Puppeteer instead, but I moved to playwright because I couldn't work out how to download a file with Pupeteer either, and the issue related to it suggested that the whole team had moved to Playwright.

4

4 回答 4

2

看看page.on("download")

const browser = await playwright.chromium.launch({});
const context = await browser.newContext({ acceptDownloads: true });
const page = await context.newPage();
await page.goto("https://somedownloadpage.weburl");
await page.type("#password", password);
await page.click("text=Continue");
const download = await page.waitForEvent("download");
console.log("file downloaded to", await download.path());
于 2021-10-21T07:59:53.270 回答
0

您可以使用waitForTimeout.

我试过{headless: true}& await page.waitForTimeout(1000);

它工作正常。你可以在这里检查

于 2020-07-13T06:40:12.547 回答
0

尴尬的是,我在下载开始之前就关闭了浏览器。

事实证明,下载错误是由该client部分引起的。但是,这意味着我无法控制文件的保存位置。

下载工作 whenheadless: false但不是 when headless: true

如果有人有更好的答案,那就太好了!

于 2020-03-03T07:03:45.007 回答
-1

要下载文件(也是它的缓冲区),我强烈推荐这个模块:得到节点模块。它更容易,清洁和轻便。

(async () => {
const response = await got('https://sindresorhus.com')
    .on('downloadProgress', progress => {
        // Report download progress
    })
    .on('uploadProgress', progress => {
        // Report upload progress
    });

    console.log(response);
})();
于 2021-10-20T04:29:14.437 回答