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.
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