如何计算具有特定类名的元素数量?

时间:2016-03-16 21:59:29

标签: nightwatch.js

如何使用nightwatch计算具有特定类名的元素数量?

例如,我想在页面上计算类名为“sample”的元素数量,并检查该数字是否大于8.如何使用nightwatch进行此操作?

3 个答案:

答案 0 :(得分:0)

我使用getEls。

client.getEls('.sample', function(collection) {
            // set the variable to be that collection's length      
            elementCount = collection.length;   
            // use the conditional for to check your collections length
            if(collection.length > 8){
                 // log the count of elements to the terminal
                 console.log("Yes. There were " + elementCount + "elements")
                // or do other things here
            }
            else{
                 // log the count of elements to the terminal
                 console.log("There were " + elementCount + "elements")
            }
            return;     
        });

答案 1 :(得分:0)

使用css或Xpath选择器。 你走了:

// use a css or Xpath selector 
client.elements(selector ,function(result) {
  return result.value.length;

});

答案 2 :(得分:0)

假设您的网页包含此标记:

<ul id="names">
    <li>Stephanie</li>
    <li>Luke</li>
    <li>Marina</li>
</ul>

你可以这样做:

module.exports = {
    'Example test': browser => {
        browser.url(browser.launchUrl);
        browser.elements('css selector', '#names li', result => {
            const numElements = result.value.length;
            console.log(numElements);
        });
    }
}

请记住,您不能在回调之外使用numElements。从回调中返回它将无济于事:browser.elements忽略返回值。在回调之前初始化numElements并在中设置其值,回调也无济于事:回调可能会在以后运行。

如果您确实需要在回调之外使用该值,则需要使用Promise

module.exports = {
    'Example test': browser => {
        browser.url(browser.launchUrl);

        const numElementsPromise = new Promise(resolve => {
            browser.elements('css selector', '#names li', result => {
                resolve(result.value.length);
            });
        });

        numElementsPromise.then(numElements => {
            console.log(numElements);
        });
    }
}