节点js selenium多循环

时间:2016-07-13 09:52:15

标签: javascript node.js selenium selenium-webdriver selenium-chromedriver

我在节点中编写了一个带有selenium webdriver的脚本,用于自动化测试。在剧本下面

var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until,
    _und = require('underscore');

var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .build();

driver.get('http://www.????.com/');
driver.wait(function() {
    driver.findElement(By.xpath("//*[@id='container']/div/div/div[1]/div[1]/div/a[1]")).then(function(link) {
        link.click();
    });
    driver.findElements(By.css("div.pu-final > span.fk-bold")).then(function(priceSpans) {
        console.log(priceSpans.length)
        _und.each(priceSpans, function(span) {
            span.getText().then(
                function(price) {
                    console.log(price)
                }
            );
        });
    });
    }, 20000);
driver.quit();

但它会在控制台中多次打印输出。

32
Rs. 5,499
Rs. 13,499
Rs. 10,999
Rs. 15,990
Rs. 8,499
Rs. 11,998
Rs. 6,999
Rs. 12,990
Rs. 7,999
Rs. 9,199
Rs. 9,990
Rs. 15,499
Rs. 9,999
Rs. 17,499
Rs. 9,999
Rs. 8,999
Rs. 8,990
Rs. 21,499
Rs. 38,499
Rs. 11,390
Rs. 10,999
Rs. 14,249
Rs. 8,999
Rs. 6,999
Rs. 6,999
Rs. 12,499
Rs. 22,999
Rs. 10,999
Rs. 18,499
Rs. 27,900
Rs. 27,900
Rs. 16,999
32
Rs. 5,499
Rs. 13,499
Rs. 10,999
Rs. 15,990
Rs. 8,499
Rs. 11,998
Rs. 6,999
Rs. 12,990
Rs. 7,999
Rs. 9,199
Rs. 9,990
Rs. 15,499
Rs. 9,999
Rs. 17,499
Rs. 9,999
Rs. 8,999
Rs. 8,990
Rs. 21,499
Rs. 38,499
Rs. 11,390
Rs. 10,999
Rs. 14,249
Rs. 8,999
Rs. 6,999
Rs. 6,999
Rs. 12,499
Rs. 22,999
Rs. 10,999
Rs. 18,499
Rs. 27,900
Rs. 27,900
Rs. 16,999

1 个答案:

答案 0 :(得分:0)

首先,你应该明白诺言是如何运作的。每个驱动程序方法都返回一个promise(将来的操作)。链接它们可以帮助您按顺序执行操作:

driver.get(url).then(function(){
  //this will be called when the webpage is loaded, i.e document ready, from
    here you should locate the element you want to click
   return driver.findElement(By.xpath....);
}).then(function(link){
    //i have not worked with web elements but i believe it should also return promise
    return link.click(); // after you click if there is some ajax response 
      //in the next function you should wait for it to appear
}).then(function(){
   return driver.wait(until.elementLocated(By.css(''));
}).then(function(){
})

希望这会有所帮助。