How to download file with puppeteer using headless: true?

前端 未结 7 1704
攒了一身酷
攒了一身酷 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:51

    setDownloadBehavior works fine for headless: true mode, and file is eventually downloaded, but throws an exception when finished, so for my case a simple wrapper helps to forget about this issue and just gets the job done:

    const fs = require('fs');    
    function DownloadMgr(page, downloaddPath) {
        if(!fs.existsSync(downloaddPath)){
            fs.mkdirSync(downloaddPath);
        }
        var init = page.target().createCDPSession().then((client) => {
            return client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: downloaddPath})
        });
        this.download = async function(url) {
            await init;
            try{
                await page.goto(url);
            }catch(e){}
            return Promise.resolve();
        }
    }
    
    var path = require('path');
    var DownloadMgr = require('./classes/DownloadMgr');
    var downloadMgr = new DownloadMgr(page, path.resolve('./tmp'));
    await downloadMgr.download('http://file.csv');
    

提交回复
热议问题