Use Java script Bookmarklet to save website data as CSV

Many times I get upset with websites, who display accounting data in a table, but don’t offer a way to download it. This includes banks, payment processors, etc. Even if they offer it, there is a chance it’s the wrong format for your purpose.

Here is a inspiration on how to use a little bit of Java script, save it as Bookmarklet and use that to export a website table to CSV

Step 1: Prepare and test Java script

In this step you can use Google Chrome’s Console or Firebug in Firefox to test your export script. This is something I use for exporting data from CurrencyFair:

[cc lang=”python” width=”100%”tab_size=”4″ lines=”40″ noborder=”1″ theme=”dawn”]
var output = ‘Date,Description,Amount,Balance\n’;
var rowsNodelist = document.querySelectorAll(‘.table tr’);
var rows = Array.prototype.slice.call(rowsNodelist, 0);
rows.slice(2, rows.length).forEach(function(row) {
var cells = row.getElementsByTagName(‘td’);
cells = Array.prototype.slice.call(cells,0);
if (cells[3].innerText.length != 0) {
output += cells[1].innerText.slice(0,-6) + ‘,’;
output += cells[2].innerText + ‘,’;
output += cells[3].innerText.replace(“,”,””).slice(0, -4) + ‘,’;
output += cells[5].innerText.replace(“,”,””).slice(0, -4) + ‘\n’;
};
});
console.log(output);

// Get month, date and year to generate filename
var d = new Date();
var curr_day = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var filename = ‘MYSITE-‘ + document.URL.slice(-14, -11) + ‘_’ + curr_year + ‘-‘ + curr_month + ‘-‘ + curr_day;

// Save as .csv file (from http://stackoverflow.com/questions/20496630)
var pom = document.createElement(‘a’);
pom.setAttribute(‘href’, ‘data:text/csv;charset=utf-8,’ + encodeURIComponent(output));
pom.setAttribute(‘download’, filename + ‘.csv’);
pom.click();
[/cc]

Step 2: Wrap in anonymous JS function.

Next you need to package your script as bookmarklet. There is a simple website who does it for you.

After crunching your script, drag+drop the Bookmarklet to your browser’s bookmark bar. Next time when you’re on the site, just klick the bookmark and you will get the CSV.