简体   繁体   English

使用页面上的相同选择器制作所有元素的屏幕截图

[英]Make screenshot of all elements with the same selector on the page

I need to make screenshot of all text with same selectors on the page. 我需要在页面上使用相同的选择器制作所有文本的屏幕截图。 For example I have 11 of the same selectors but with different text on the page. 例如,我有11个相同的选择器,但页面上的文本不同。

But when I use "repeat" I can't do it. 但是,当我使用“重复”时,我做不到。 It only capture the first selector 11 times. 它仅捕获第一个选择器11次。

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

Doing the same thing over and over again and expecting different results ... may happen in web browser testing, but not in this case. 一遍又一遍地做同样的事情,并期望得到不同的结果……可能会在网络浏览器测试中发生,但在这种情况下不会发生。 In this case you're repeating the same task over and over again with the same selector. 在这种情况下,您将使用相同的选择器一遍又一遍地重复相同的任务。 You need to iterate over the selectors. 您需要遍历选择器。

This will not work using CSS selectors because :nth-of-type() for example means the nth element under the same parent, which may not be the case for your site. 这不适用于CSS选择器,因为例如:nth-of-type()表示同一父级下的第n个元素,对于您的网站可能并非如此。

You should use an XPath expression to do this. 您应该使用XPath表达式来执行此操作。 CasperJS provides an XPath utility to make it easier invoking them: 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)+"]"));
    });
});

What this XPath means: 这个XPath意味着什么:

  • //*[contains(@class,'annotation')] selects all .annotation elements as a node list. //*[contains(@class,'annotation')]选择所有.annotation元素作为节点列表。
  • "(//*[contains(@class,'annotation')])["+(index+1)+"]" selects the index+1 'th element from the node list. "(//*[contains(@class,'annotation')])["+(index+1)+"]"从节点列表中选择第index+1个元素。 Counting starts with 1 in XPath expressions XPath表达式中的计数从1开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM