Actor

jancurn/cz-president-election

  • Builds
  • latest 0.0.15 / 2018-01-11
  • Created 2018-01-11
  • Last modified 2018-09-18
  • grade 2

Description

Collects voting data from Czech statistical office about the Czech presidential election 2018.


API

To run the actor, send a HTTP POST request to:

https://api.apify.com/v2/acts/jancurn~cz-president-election/runs?token=<YOUR_API_TOKEN>

The POST payload will be passed as input for the actor. For more information, read the docs.


Example input

Content type: application/json; charset=utf-8

{ "hello": 123 }

Source code

Based on the apify/actor-node-basic Docker image (see docs).

const Apify = require('apify');
const request = require('request-promise');
const iconv = require('iconv-lite');

// Downloads XML file, returns null on error
const downloadXml = async (url) => {
    console.log(`Downloading ${url}`);
    try {
        const xml = await request({
            url: 'https://www.volby.cz/pls/prez2018/vysledky',
            encoding: null,
        });
        return iconv.decode(xml, 'iso-8859-2');
    } catch(e) {
        console.log(e);
        return null;
    }
};

// Taken from https://www.volby.cz/opendata/prez2018/PREZ_nuts.htm
const allNuts = [
    "CZ010", "CZ020", "CZ031", "CZ032", "CZ041", "CZ042", "CZ051", "CZ052", "CZ053", 
    "CZ063", "CZ064", "CZ071", "CZ072", "CZ080"
];

// Election round (1 or 2)
const kolo = 1;

Apify.main(async () => {;
    
    const vysledky = {
        crawledAt: new Date(),
    };
    
    vysledky.celkove = await downloadXml('https://www.volby.cz/pls/prez2018/vysledky');
    
    console.log('Sample data:');
    console.log(vysledky.celkove);
    
    vysledky.kraj = {};
    for (let i=0; i<allNuts.length; i++) {
        const nuts = allNuts[i];
        vysledky.kraj[nuts] = await downloadXml(`https://www.volby.cz/pls/prez2018/vysledky_kraj?kolo=${kolo}&nuts=${nuts}`);
    }
    
    vysledky.krajmesta = await downloadXml(`https://www.volby.cz/pls/prez2018/vysledky_krajmesta?kolo=${kolo}`);
    vysledky.zahranici = await downloadXml(`https://www.volby.cz/pls/prez2018/vysledky_zahranici?kolo=${kolo}`);
    
    // Store data to named key-value store
    const store = await Apify.client.keyValueStores.getOrCreateStore({
        storeName: 'cz-presidential-election-2018'
    });
    
    console.log('Store info:');
    console.dir(store);

    await Apify.client.keyValueStores.putRecord({
        storeId: store.id,
        key: 'vysledky_' + vysledky.crawledAt.toISOString().replace(/:/g, '-'),
        body: JSON.stringify(vysledky, null, 2),
        contentType: 'application/json; charset=utf-8',
    });
});