How to download file with puppeteer using headless: true?

前端 未结 7 1689
攒了一身酷
攒了一身酷 2020-12-08 05:05

I\'ve been running the following code in order to download a csv file from the website http://niftyindices.com/resources/holiday-calendar:

7条回答
  •  一生所求
    2020-12-08 05:33

    I needed to download a file from behind a login, which was being handled by Puppeteer. targetcreated was not being triggered. In the end I downloaded with request, after copying the cookies over from the Puppeteer instance.

    In this case, I'm streaming the file through, but you could just as easily save it.

        res.writeHead(200, {
            "Content-Type": 'application/octet-stream',
            "Content-Disposition": `attachment; filename=secretfile.jpg`
        });
        let cookies = await page.cookies();
        let jar = request.jar();
        for (let cookie of cookies) {
            jar.setCookie(`${cookie.name}=${cookie.value}`, "http://secretsite.com");
        }
        try {
            var response = await request({ url: "http://secretsite.com/secretfile.jpg", jar }).pipe(res);
        } catch(err) {
            console.trace(err);
            return res.send({ status: "error", message: err });
        }
    

提交回复
热议问题