在phantomjs中使用"window.onload"

khe*_*hex 1 node.js phantomjs

我正在使用PhantomJS通过npm-phantom模块从基于AJAX的页面中抓取数据.有时,当幻像启动DOM遍历时,数据仍未加载.如何插入类似window.onload = function() { ... }的内容page.evaluate?它返回一个函数,但不是数据.

var phantom = require('phantom');

exports.main = function (url, callback) {
    phantom.create(function (ph) {
        ph.createPage(function (page) {
            page.open(pref + url, function (status) {
                page.evaluate(function () {
                    // here  
                    var data = {};
                    data.one = document.getElementById("first").innerText;
                    data.two = document.getElementById("last").innerText;
                    return data;
                },
                function (res) {
                    callback(null, res);
                    ph.exit();
                });
            });
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

在PhantomJS API页面上我找到了onLoadFinished,但它是如何应用的.

Art*_* B. 5

page.open(url, function(status){...}) 只是另一种表示法

page.onLoadFinished = function(status){...};
page.open(url);
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到报价:

另请参阅回调WebPage#open的备用挂钩onLoadFinished.


由于这是一个基于AJAX的页面,您需要等待数据出现.您只能通过反复检查页面的特定部分来实现.

您可以在phantomjs 安装示例目录中找到示例或此处.这可能也适用于通过npm-phantom的phantomjs.

在你的情况下,这将是这样(缩写):

page.open(pref + url, function (status) {
   waitFor(function check(){
       return page.evaluate(function () {
           // ensure #first and #last are in the DOM
           return !!document.getElementById("first") && 
                  !!document.getElementById("last");
       });

   }, function onReady(){
       page.evaluate(function () {
           var data = {};
           data.one = document.getElementById("first").innerText;
           data.two = document.getElementById("last").innerText;
           return data;
        });
        callback(null, res);
        ph.exit();
   }, 5000); // some timeout
});
Run Code Online (Sandbox Code Playgroud)