How to download file with puppeteer using headless: true?

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

    This page downloads a csv by creating a comma delimited string and forcing the browser to download it by setting the data type like so

    let uri = "data:text/csv;charset=utf-8," + encodeURIComponent(content);
    window.open(uri, "Some CSV");
    

    This on chrome opens a new tab.

    You can tap into this event and physically download the contents into a file. Not sure if this is the best way but works well.

    const browser = await puppeteer.launch({
      headless: true
    });
    browser.on('targetcreated', async (target) => {
        let s = target.url();
        //the test opens an about:blank to start - ignore this
        if (s == 'about:blank') {
            return;
        }
        //unencode the characters after removing the content type
        s = s.replace("data:text/csv;charset=utf-8,", "");
        //clean up string by unencoding the %xx
        ...
        fs.writeFile("/tmp/download.csv", s, function(err) {
            if(err) {
                console.log(err);
                return;
            }
            console.log("The file was saved!");
        }); 
    });
    
    const page = await browser.newPage();
    .. open link ...
    .. click on download link ..
    
    0 讨论(0)
提交回复
热议问题