问题 Phantom.js中的setTimeout


下面的代码希望Phantom.js加载页面,单击按钮并等待5秒钟,然后返回页面的HTML代码。

问题: 然而使用 setTimeout() 创建5秒延迟导致 page.evaluate 功能返回 null 到回调函数而不是HTML。

myUrl = 'http://www.google.com'

var phantom = Meteor.npmRequire('phantom')
phantom.create = Meteor.wrapAsync(phantom.create)
phantom.create( function(ph) {

    ph.createPage = Meteor.wrapAsync(ph.createPage)
    ph.createPage(function(page) {

        page.open = Meteor.wrapAsync(page.open)
        page.open(listingUrl, function(status) {
            console.log('Page loaded')

            page.evaluate = Meteor.wrapAsync(page.evaluate)
            page.evaluate(function() {

                // Find the button
                var element = document.querySelector( '.search-btn' );

                // create a mouse click event
                var event = document.createEvent( 'MouseEvents' );
                event.initMouseEvent( 'click', true, true, window, 1, 0, 0 );

                // send click to element
                element.dispatchEvent( event );

                // Give page time to process Click event
                setTimeout(function() {
                    // Return HTML code
                    return document.documentElement.outerHTML
                }, 5000)

            }, function(html) {

                // html is `null`
                doSomething()

            })
        })
    })
})

更换 setTimeout() 同 Meteor.setTimeout() 导致另一个错误:

phantom stdout: ReferenceError: Can't find variable: Meteor

10168
2018-03-09 19:52


起源



答案:


page.evaluate() 是PhantomJS的沙盒页面上下文。它无法访问外部定义的变量。如果您需要超时,则需要进行两次调用 page.evaluate(),因为你不能从异步函数返回任何东西(说明):

page.evaluate(function() {
    ...
    element.dispatchEvent( event );
}, function() {
    setTimeout(function() {
        page.evaluate(function() {    
            return document.documentElement.outerHTML
        }, function(html) {
            doSomething()
        })
    }, 5000)
})

而不是使用第二个 page.evaluate() 呼叫,您可以通过直接访问定义的内容来缩短代码 这里

setTimeout(function() {
    page.get("content", function(content) {
        doSomething()
    })
}, 5000)

9
2018-03-09 20:02





这不是一个很好的解决方案,但如果您只想处理按钮点击和表单提交的页面更改,则可以使用。 只需在page.open()之外声明函数变量,然后在里面为它们分配页面评估函数。在页面重新加载按钮单击后的更改后,将调用onLoadFinished,然后您可以再次对其进行评估。

var loadInProgress = false,
jurl = 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
page = require('webpage').create();

// declare variables outside page.open and assign them later inside
var evalPageFunc;

// assign callbacks which will be called by phantom
page.onLoadStarted = function() {
    loadInProgress = true;
    console.log('load started');
};
page.onLoadFinished = function() {
    loadInProgress = false;
    console.log('load finished');
    if (evalPageFunc) {
      // since the page has loaded we can safely evaluate it
      var mydata = evalPageFunc();
      console.log(mydata);
      if (!mydata.havemore) {
        phantom.exit();
        // or next url
      }
    }
};

page.open(url, function(status) {
  page.includeJs(jurl, function(){

    // define your page evaluating functions
    evalPageFunc = function(){
      return page.evaluate(function() {
        var datafromhtml = {}, havemoretoclick = true;
        // get your data and perform clicks if you want to
        // datafromhtml.somedata = $('stealme').text();
        // $("clickme").click();
        return {
          havemore: havemoretoclick,
          data: datafromhtml
        };
      });
    }
    var k = evalPageFunc();
  });
});

它不漂亮,但它的工作原理。


0
2017-07-22 23:12