define page evaluate outside of page open in phantomjs

隐身守侯 提交于 2019-12-10 19:27:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!