How to use Phantomjs to access a JSON responsive API

Asked

Viewed 224 times

1

How to use PhantomJS to access an API whose response is JSON and not HTML and process the result?

I would like the example to use the Stackoverflow API itself in English, so that the script returns the title and names of the authors of recently changed questions.

1 answer

1


To do this, go to the API interface and find out which URL to use. For this specific case, this is the direct link https://api.stackexchange.com/docs/no-answer-questions#order=desc&sort=activity&filter=default&site=en.stackoverflow&run=true

The code below is documented and details how to do this

var page = require('webpage').create();

// Acesse perguncas recentes do pt.stackoverflow
page.open('https://api.stackexchange.com/2.1/questions/no-answers?order=desc&sort=activity&site=pt.stackoverflow', function () {
    var objeto = null, i = 0;

    try {
        // page.plainText retorna o conteúdo da página pura, sem forçar tags HTML em volta e invalidar a resposta como JSON
        objeto = JSON.parse(page.plainText);
    } catch (e) {
        console.log('Erro ao processar resposta em JSON');
    }
    if (objeto && objeto.items && objeto.items.length) {
        for (i = 0; i < objeto.items.length; i +=1) {
            console.log(objeto.items[i].title + ' por ' + objeto.items[i].owner.display_name);
        }
    }
    phantom.exit(); // Finaliza
});

It will print something like

java.lang.NullPointerException em sistema de chat por Luiz
Como trabalhar OO com Banco de Dados no Delphi? por Arthur de Andrade
Como criar uma AVD para Android em Delphi por Luiz
(...)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.