在CasperJS中你如何进行等待工作?

时间:2016-04-26 01:25:40

标签: javascript dom click wait casperjs

为什么要等待ClickOldShares'不管用?即使我在评估中,等待也不起作用。我相信这是一个带引用的小细节,但我现在没有想法。

function clickOldShares(){
  console.log("Waiting for Old Shares");
  element = document.querySelector("#pagelet_scrolling_pager > div > div > a"); 
  console.log("ELEMENT: " + element);
  if(element){
    console.log('click and waiting...');
    element.click();
    console.log('clicked!'+ element);

    //THIS WAIT IS NOT WORKING!!!! I DON'T KNOW WHY!!!!
    this.wait(2000,clickOldShares);

  }
  else {
    console.log("done!");
  }
  return element;
};

//Initializing Casper
casper.start('https://www.facebook.com/', function() {
   console.log("Entering on Facebook"); 
});

//Remote Message Handler - now I can see what happen inside evaluates
casper.on('remote.message', function(msg) {
  this.echo(msg);
})


//Facebook login
casper.then(function(){
    console.log("Login using username and password");
    this.evaluate(function(){
      document.getElementById("email").value = 'foo@bar';
      document.getElementById("pass").value = 'somepass';
      document.getElementById("login_form").submit();
      })
    if(this.exists('#u_0_2 > div:nth-child(1) > div:nth-child(1) > div > a > span')){
      console.log("Login ok!");
    }
    else {
      console.log("Login not ok!");
      casper.exit();
    }
});


    casper.thenOpen("https://www.facebook.com/shares/view?id=1063249230414580" ,function(){
    console.log("Open post with object-id");
  });


casper.thenClick("#pagelet_scrolling_pager > div > div > a",function(){ 
      this.wait(2000,function(){ this.evaluate(clickOldShares)});
 });

1 个答案:

答案 0 :(得分:0)

页面上下文(this内)的

casper.evaluate()指的是window而不是casper。您无法在页面上下文中使用casper

你需要移动东西:

function clickOldShares(){
    var elementAvailable = this.evaluate(function(){
      console.log("Waiting for Old Shares");
      element = document.querySelector("#pagelet_scrolling_pager > div > div > a"); 
      console.log("ELEMENT: " + element);
      if(element){
        console.log('click and waiting...');
        element.click();
        console.log('clicked!'+ element);
      }
      return !!element;
    });
    if (elementAvailable) {
      this.wait(2000, clickOldShares);
    }
};

并像这样使用它:

casper.thenClick("#pagelet_scrolling_pager > div > div > a",function(){ 
    this.wait(2000, clickOldShares);
});

由于无法传递DOM节点,因此需要在页面上下文中存在DOM元素的某种表示形式。这可以通过使用!element将DOM节点强制转换为布尔值然后立即取消!!element以检查element是否为“真实”来轻松实现。