Scraping Transaction Data from KBC Bank

In a previous post, I mentioned importing transactions using ledger/hledger and plain text accounting. As my former bank PTSB recently raised their fees, I decided to move to KBC. I was excited to see, as part of the open payments directive, they have a nice developer portal. I reached out to KBC’s dev team, but alas they are only accepting registered companies, who meet stringent criteria. They told me they hope to open it up soon to end users, I live in hope!

Another piece of bad news is that KBC online banking has no way to download transactions! Also I couldn’t re-use my previous python script as KBC make heavy use of two-factor authentication, meaning I’d have to enter a code anyway. Plus I could rework the script, only to get access to the proper API and have to do it again. So I decided to log in to KBC manually, then use a Javascript bookmarklet to downloacd the transactions from the table.

Here’s the bookmarklet:

javascript:(function(){function downloadCSV(csv,filename){let csvFile;let downloadLink;csvFile=new Blob([csv],{type:"text/csv"});downloadLink=document.createElement("a");downloadLink.download=filename;downloadLink.href=window.URL.createObjectURL(csvFile);downloadLink.style.display="none";document.body.appendChild(downloadLink);downloadLink.click()};function exportTableToCSV(filename){let csv=[];let rows=document.querySelectorAll(".table-transactions tr");for(var i=0;i<rows.length;i+=1){let row=[],cols=rows[i].querySelectorAll("td, th");for(var j=0;j<cols.length;j+=1){let txt=cols[j].innerText;txt=txt.replace("-","");txt=txt.replace(",","");row.push(txt)}csv.push(row.join(","))}downloadCSV(csv.join("\n"),filename)}exportTableToCSV("kbc.csv")})();

Simply add a new bookmark to your broswer, past the code above for the URL, then log in to KBC online banking and click your bookmark. It’s still a bit rough around the edges (I didn’t cater for the pagination, so it only dumps one page of transactions). But I can now get a CSV copy of the transactions, and I keep my ledger file happy (for now)!