Converting an array of promises from Selenium's findElements into an array of objects

会有一股神秘感。 提交于 2019-12-07 22:09:20

问题


I am using Selenium with node.js I am trying to do the following

var driver   = *webdriver instance*;
var my_xpath = *an xpath string*;
var ele;

Q.all(driver.findElements(webdriver.By.xpath(my_xpath))).then(function(elements) {
    for (ele in elements) {
        console.log(ele.getText());
    };
}

I was under the impression that Q.all would convert the array of promises returned by driver.findElements into an array of values so that when I output ele.getText() it would be a value. However in this case the ele is still a promise.

What am I missing here?

Note that I realise that for the above example this is unnecessary and I can simple use a ele.getText().then, but my actual program requires having all the values before proceeding.


回答1:


There's no need to aggregate the promises with all since findElements returns a single promise. You also need to iterate the resolved array with a for loop and not a for-in loop:

driver.findElements(webdriver.By.xpath(my_xpath)).then(function(elements) {
    for (var i = 0; i < elements.length; i++) {
        elements[i].getText().then(function(text) {
            console.log(text);
        })
    };
});

You could also use map to directly get an array with the text for each element :

var map = webdriver.promise.map;

var elements = driver.findElements(By.xpath(my_xpath));

map(elements, e => e.getText()).then(function(texts) {
  console.log(texts);
});


来源:https://stackoverflow.com/questions/38146870/converting-an-array-of-promises-from-seleniums-findelements-into-an-array-of-ob

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!