【问题标题】:Use "window.onload" in phantomjs在 phantomjs 中使用“window.onload”
【发布时间】:2014-07-21 12:46:28
【问题描述】:

我正在使用 PhantomJS 通过npm-phantom 模块从基于 AJAX 的页面中抓取数据。有时当 phantom 开始 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();
                });
            });
        });
    });
}

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

【问题讨论】:

    标签: node.js phantomjs


    【解决方案1】:

    page.open(url, function(status){...}) 只是

    的另一种表示法
    page.onLoadFinished = function(status){...};
    page.open(url);
    

    你可以找到报价here

    另请参阅 WebPage#open 以了解 onLoadFinished 回调的备用挂钩。


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

    您可以在 phantomjs 安装hereexamples 目录中找到示例。这可能也适用于通过 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
    });
    

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 2021-10-17
      • 1970-01-01
      • 2012-10-15
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多