2016-01-20 112 views
3

我試圖通過鏈接列表循環,並對每個鏈接執行一些操作。我可以使用elements迭代元素,但在forEach中使用click並不會阻止forEach中的下一步,而Selenium會堅持下去,因爲它試圖繼續對不在DOM中的元素執行操作。WebdriverIO中的循環元素

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。我用更具體的東西更新了我的代碼示例。

回答

1

this response從WebdriverIO的創造者,通過一些鏈接正確地遍歷並點擊它們:

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); 
    }); 
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

+0

我應該提到,我已經嘗試過的解決方案,我可以在github。我更新了我的問題。抱歉。 – danielsvane

0

你可能想使用異步包類似的東西。

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() { 
    //... 
});