PhantomJS includeJS не работает - PullRequest
0 голосов
/ 18 мая 2018

Я пытаюсь использовать PhantomJS для получения данных с такого сайта:

app.get('/scrape', function(req, res) {
var _ph, _page;
phantom.create()
.then(function (ph) {
    _ph = ph;
    return ph.createPage();
})
.then(function (page) {
    _page = page; 
    var url = "https://banc.nl/";
    return page.open(url);
})
.then(function(page) {
    page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js', function() {
    page.evaluate(function() {
        $('.sc-dnqmqq kaMmif').filter(function () {
            var data = $(this);
            price = data.children().first().text();
            console.log("Price: " + price);
        });
    });
    });
})
.catch(function(err) {
    console.log("Error: " , err);
    _page.close();
    //_ph.exit();
});
});

Проблема в том, что я получаю следующую ошибку: Error: TypeError: page.includeJs is not a function

Если я раскомментирую ph.exit(), я также получу предупреждение: warn: exit() was called before waiting for commands to finish. Make sure you are not calling exit() prematurely.

Я нашел несколько вопросов по этому поводу в SO, но ни один из ответов не решил мою проблему.

1 Ответ

0 голосов
/ 18 мая 2018

Последняя версия модуля phantomjs-node использует Promises, поэтому мы можем переписывать сценарии с использованием функций async с оператором await - гораздо более читабельным:

var phantom = require('phantom');
var url = 'https://www.huobipro.com';

(async function(req, res) {
    const instance = await phantom.create();
    const page = await instance.createPage();

    await page.on('onConsoleMessage', function(msg) {
        console.info(msg);
    });
    await page.on('onError', function(msg) {
        console.info(msg);
    });

    const status = await page.open(url);
    await console.log('STATUS:', status);

    // Wait a bit for javascript to load and run
    await new Promise(resolve => setTimeout(resolve, 3000))

    await page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js');
    await page.evaluate(function() {
        $('span[price]').filter(function () {
            var data = $(this);
            console.log("Price: " + data.text());
        });
    });

    await instance.exit();
})();
...