2014-11-05 20 views
0

我需要使用页面上的相同选择器制作所有文本的屏幕截图。例如,我有11个相同的选择器,但页面上的文本不同。使用页面上的相同选择器制作所有元素的屏幕截图

但是,当我使用“重复”,我不能做到这一点。它只捕捉第一个选择器11次。

casper.repeat(11, function() { 
    casper.captureSelector(Math.random()+".png", ".annotation"); 
}); 

回答

0

一遍又一遍地做同样的事情,并期待不同的结果...可能发生在Web浏览器测试中,但在这种情况下不会发生。在这种情况下,您使用相同的选择器一遍又一遍地重复执行相同的任务。您需要遍历选择器。

这不会使用CSS选择器,因为:nth-of-type()例如意味着在同一父母下的第n个元素,这可能不是您的网站的情况。

您应该使用XPath表达式来执行此操作。 CasperJS提供一个XPath工具,使其更容易调用它们:

var x = require('casper').selectXPath; 
casper.then(function(){ 
    var elements = this.getElementsInfo(".annotation"); // for correct count 
    elements.forEach(function(_el, index){ 
     // don't need the element info, this was done just for count 
     casper.captureSelector(Math.random()+"_"+index+".png", x("(//*[contains(@class,'annotation')])["+(index+1)+"]")); 
    }); 
}); 

这是什么意思的XPath:

  • //*[contains(@class,'annotation')]选择所有.annotation元素作为节点列表。
  • "(//*[contains(@class,'annotation')])["+(index+1)+"]"从节点列表中选择index+1'th元素。从XPath表达式中的1开始计数
+0

完美工作,谢谢)) – starkif 2014-11-05 10:46:37