首页 > 解决方案 > 将纯 JS 控制台日志或变量保存到 CSV

问题描述

我需要您的专业知识如何将 console.log 输出或变量保存到 csv 文件中?请检查我下面的代码谢谢!

jQuery('.result-row').each(function(index, value) {
    var name = jQuery(this).find('a.result-name span').text();
    var occupation = jQuery(this).find('span.result-suffix.result-suffix-verified').text();
    var occupationwospace = occupation.replace(/\s \s/g, '')
    console.log(name + '\t' + occupationwospace );
});

标签: javascripthtmljquerycss

解决方案


一种方法是使用Blob 对象

let csv = ""; // CSV Content will be placed here

jQuery('.result-row').each(function(index, value) {

    let name = jQuery(this).find('a.result-name span').text();
    let occupation = jQuery(this).find('span.result-suffix.result-suffix-verified').text();
    let occupationwospace = occupation.replace(/\s \s/g, '')
    csv += name + '\t' + occupationwospace + '\n'; // Append to CSV String variable

});

const blob = new Blob([csv], {type: "text/csv;charset=utf-8"});
const blobUrl = URL.createObjectURL(blob);

// Create a link to download the file
const link = document.createElement("a");
link.href = blobUrl;
link.download = "data.csv";
link.innerHTML = "Click here to download the file";
document.body.appendChild(link);
// link.click(); // Auto download

推荐阅读