在phantomjs中使用“window.onload”

我使用PhantomJS通过npm-phantom模块从基于AJAX的页面中抓取数据。 有时数据在幻像开始DOM遍历时尚未加载。 如何在page.evaluate插入类似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页面上,我find了onLoadFinished ,但它是如何应用的。

page.open(url, function(status){...})只是另一个符号

 page.onLoadFinished = function(status){...}; page.open(url); 

你可以在这里find报价:

另请参阅WebPage#打开 onLoadFinishedcallback的备用钩子。


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

您可以在phantomjs 安装示例目录或这里find一个示例。 这也可能通过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 });