您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用headless使用puppeteer下载文件:true?

如何使用headless使用puppeteer下载文件:true?

页面通过创建逗号分隔的字符串并通过设置数据类型来强制浏览器下载csv,从而下载csv

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

chrome上的此按钮会打开一个标签

您可以点击此事件,然后将内容实际下载到文件中。不知道这是否是最好的方法,但是效果很好。

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 ..
其他 2022/1/1 18:19:33 有308人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶