问题
in the basic example of open a web page with phantomjs we use below code for open web and evaluate when page open complete in a function .
var page = require('webpage').create();
page.open('http://www.sample.com', function() {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
console.log(document.title);
});
phantom.exit()
});
});
is any way that let us define page.evaluate in a function out side of page.open callback function for call it any time we need and no just after page open
回答1:
not sure what exactly do you mean, but from what I've understood from your example this could help maybe:
var page = require('webpage').create();
// document is already initialized
document.title = 'internal call';
page.onConsoleMessage = function (msg, lineNum, sourceId) {
console.log('PAGE\'S CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};
var func = function () {
console.log('Title: ', document.title);
}
// calling outside of the page.open:
func();
page.open('http://google.com/', function () {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
// calling inside:
page.evaluate(func);
page.close();
phantom.exit(0);
});
});
Also there is a Note for page.evaluate function about arguments and closures
来源:https://stackoverflow.com/questions/22415327/define-page-evaluate-outside-of-page-open-in-phantomjs