How to Download CSV File with Google Puppeteer

September 27, 2022

I’m building an personal finance app where I’m aggregating all financial transactions from all the bank/credit card statements.

Recently, my primary bank started providing a way to download CSV statements from web portal that I can access using a unique link that I get every month in email.

So I’ve started automating the workflow in which I download the csv and then do data clean up.

Here’s how I download the csv file from the website.

Dependency

We’ll be using Google Puppeteer to automate the workflow. Puppeteer provides the way to control and interact with your chrome/chromium browser via Node.js. So you can pretty much do anything that you can do in the browser via code.

Step 1: Install the package

Install the package in your node project

mkdir -p  download-csv-puppeteer && $_
npm init -y
npm install puppeteer
touch index.js

Step 2: Download the CSV file

// index.js
const puppeteer = require('puppeteer');
const path = require('path');

// We're creating the a new directory inside current directory where the file will be downloaded
const downloadPath = path.resolve('./download');

(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    const client = await page.target().createCDPSession();
    await page.goto('https://nesinio-pptr-csv-download.surge.sh', { waitUntil: "networkidle2" });
    await page.waitForSelector(`#downloadLink`)
    await client.send('Page.setDownloadBehavior', {
        behavior: 'allow',
        downloadPath: downloadPath
    });
    await page.click('#downloadLink')
    await browser.close();
})();

Step 3: Now run it

node index.js

Once the browser opens and closes, you should be seeing a new file in ./downloads/ directory :)

Sample repo and demo

I’ve created a sample repo for you to playaround :)

https://github.com/AshikNesin/nesinio-example-csv-download-pptr

References


👋 I'm Ashik Nesin • Principal Software Engineer @Chargebee 👨‍💻• I write about web development & behinds the scenes of startup/side projects that I'm building

© 2022 Nesin Technologies LLP