Call function PhantomJs

…衆ロ難τιáo~ 提交于 2019-12-04 19:26:28

It seems that the function set_calendar_date when executed will load content through ajax or do some processing to generate content. This content will be placed somewhere, possibly inside an element with id fs.

Considering the asynchronous nature of this process, you can not directly return the innerHTML just after calling the function (you may either get the old data or nothing at all).

What I would suggest is to call the function inside evaluate

    page.evaluate(function () {
        set_calendar_date('1');
    });

Next, you need to understand the nature of the "update". Find an element that can help in programmatically determine that the update is complete or not-yet-complete. Say, for instance, if the innherHTML of the element with id fs is empty the content is not yet updated.

And then keep checking for change in the target element (vis, fs). You can keep checking this using window.setInterval.

The code can be similar to:

page.evaluate(function () {
   set_calendar_date('1');
});

var waiter = window.setInterval(function(){
  var fsContent = page.evaluate(function(){
     var elm = document.getElementById('fs');
     return elm && elm.innerHTML || false;
  });
  // if content is found
  if (fsContent !== false) {
     window.clearInterval(waiter);
     var file= require('fs');
     file.write('results.txt',fsContent,'w+');
  }

}, 300);

NOTE: This can be implemented with simpler code using CasperJS, a wrapper around PhantomJS. CasperJS provides a number of functions to do this easily like using waitForSelectorTextChange() or waitFor(), waitForSelector() or waitWhileSelector() etc.

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