调用函数PhantomJs [英] Call function PhantomJs

查看:165
本文介绍了调用函数PhantomJs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java Script的新手,我需要帮助:)
我想调用函数(set_calendar_date())然后获取页面innerHTML。

I'm new in Java Script and i need help :) I want to call function ( set_calendar_date() ) and then get page innerHTML.

<a onclick="set_calendar_date('1'); return false;" href="#">

<span>

    26/02 We

</span>

PhantomJs代码:

PhantomJs code :

page.open(url, function (status) {
if (status !== 'success') 
{
            console.log('Unable to access network');
    } 
else 
{
    var events = page.evaluate(function () {
            // here i want to call set_calendar_date();
            return document.getElementById('fs').innerHTML;
        });
    var file= require('fs');
    file.write('results.txt',events,'w+');

phantom.exit();
}});


推荐答案

似乎函数 set_calendar_date 执行时将通过ajax加载内容或进行一些处理以生成内容。此内容将放置在某个位置,可能位于id fs 的元素内。

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.

考虑此过程的异步性质,你不能在调用函数后直接返回 innerHTML (你可能要么得到旧数据,要么什么都没有)。

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');
    });

接下来,您需要了解更新的性质。找到一个有助于以编程方式确定更新已完成或尚未完成的元素。比如说,如果id fs 的元素的 innherHTML 为空,则内容尚未更新。

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.

然后继续检查目标元素的变化(vis, fs )。您可以使用 window.setInterval 继续检查。

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

代码类似于:

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);

注意:这可以使用CasperJS(PhantomJS的包装器)使用更简单的代码来实现。 CasperJS提供了许多功能来轻松完成,例如使用 waitForSelectorTextChange() waitFor() waitForSelector() waitWhileSelector()等。

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.

这篇关于调用函数PhantomJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆