How to download file with puppeteer using headless: true?

前端 未结 7 1705
攒了一身酷
攒了一身酷 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 05:53

    The problem is that the browser closes before download finished.

    You can get the filesize and the name of the file from the response, and then use a watch script to check filesize from downloaded file, in order to close the browser.

    This is an example:

    const filename = ;
    const dir = ;
    
    // Download and wait for download
        await Promise.all([
            page.click('#DownloadFile'),
           // Event on all responses
            page.on('response', response => {
                // If response has a file on it
                if (response._headers['content-disposition'] === `attachment;filename=${filename}`) {
                   // Get the size
                    console.log('Size del header: ', response._headers['content-length']);
                    // Watch event on download folder or file
                     fs.watchFile(dir, function (curr, prev) {
                       // If current size eq to size from response then close
                        if (parseInt(curr.size) === parseInt(response._headers['content-length'])) {
                            browser.close();
                            this.close();
                        }
                    });
                }
            })
        ]);
    

    Even that the way of searching in response can be improved though I hope you'll find this usefull.

提交回复
热议问题