WebdriverIO中的循环元素

时间:2016-01-20 20:05:48

标签: node.js selenium selenium-webdriver webdriver-io

我正在尝试遍历链接列表,并对每个链接执行一些操作。我可以使用elements迭代元素,但在forEach中使用click不会阻止forEach的下一步,Selenium会疯狂,因为它试图继续对不在DOM中的元素执行操作了。

var q = require("q");
var webdriverio = require('webdriverio');
var options = {
    desiredCapabilities: {
        browserName: 'chrome'
    }
};

var clicks = [];

var runner = webdriverio.remote(options);

runner
    .init()
    .url('https://www.google.dk/search?q=burrito')
    .elements(".r").then(function(res){
        res.value.forEach(function(elem){
            console.log(elem);
            clicks.push(
                runner
                    .elementIdClick(elem.ELEMENT)
                    .pause(5000)
                    .back()
                    .pause(2000)
            );
        });

        return q.all(clicks);
    });

如何在forEach中执行所有代码之前确保forEach中的下一次迭代没有运行?

编辑:我应该提到我已经尝试https://github.com/webdriverio/webdriverio/issues/941https://github.com/webdriverio/webdriverio/issues/273了。我用更具体的内容更新了我的代码示例。

4 个答案:

答案 0 :(得分:3)

var runner = webdriverjs
.remote(options)
.init()
.url("http://www.google.com")

 // fetch elements
.elements('a', function(err, res){
    // iterate through elements
    res.value.forEach(function(elem) {
        // execute specific action
        runner.elementIdClick(elem.Element, function(err, res) {
             // callback logic here
             // ...
        })
    })
})

来自https://github.com/webdriverio/webdriverio/issues/273

答案 1 :(得分:1)

根据来自WebdriverIO创建者的this response,循环访问某些链接并单击它们的正确方法:

runner
    .init()
    .url('https://www.google.dk/search?q=burrito')
    .getText(".r").then(function(res){
        console.log(res);
        res.forEach(function(elem){
            console.log(elem);
            clicks.push(
                runner
                    .click('=' + elem)
                    .back()
            );
        });

        return q.all(clicks);
    });

答案 2 :(得分:0)

您可能希望使用Async软件包。

http://caolan.github.io/async/

async.eachSeries(hugeArray, function iteratee(item, callback) {
    if (inCache(item)) {
        callback(null, cache[item]); // if many items are cached, you'll overflow
    } else {
        doSomeIO(item, callback);
    }
}, function done() {
    //...
});

答案 3 :(得分:0)

从元素列表中提取文本的简单方法

I am able to extract text for the list of webelements and then store it to the Array .


var strColumntext = [] ;
    var table =browser.$(".//*/table/tbody");

   table.$$(".//tr/th").map(function(element){
         console.log("Extracted text is : "+element.getText());
         strColumntext.push(element.getText());
    });
    
    console.log("Print the all texts : "+strColumntext)

You can see Youtube Demo for this

相关问题