从findElement(By.className())获取元素数组 [英] get an array of elements from findElement(By.className())
问题描述
我正在用node.js中的Selenium编写脚本,该脚本将转到页面并获取某个CSS类的innerhtml并将其存储在数组中.
I am writing a script in node.js for selenium that will go to a page and grab the innerhtml of a certain css class and store them in an array.
var element = driver.findElement(By.className("hll"));
element.getInnerHtml().then(html){
//returns 1 of the elements html where I want multiples
}
推荐答案
To retrieve the html of multiple elements, you can use driver.findElements()
to find all matches elements. This will provider a Promise
that resolves with the elements in an Array
.
var pendingElements = driver.findElements(By.className('h11'))
pendingElements.then(function (elements) {
// ...
});
您将需要遍历集合并请求每个元素的HTML.您可以使用Array
的 getInnerHtml()
创建承诺的集合:
You'll need to iterate over the collection and request each element's HTML. You can use the Array
's .map()
to create a collection of promises from getInnerHtml()
:
var pendingHtml = elements.map(function (elem) {
return elem.getInnerHtml();
});
To wait for them to be resolved, you can pass the collection to promise.all()
.
promise.all(pendingHtml).then(function (allHtml) {
// ...
});
注意,为此,您需要引用Selenium的promise
.
Note, you'll need a reference to Selenium's promise
for that.
var promise = require('selenium-webdriver').promise;
组合:
Combined:
// ...
var promise = require('selenium-webdriver').promise;
var pendingElements = driver.findElements(By.className('h11'))
pendingElements.then(function (elements) {
var pendingHtml = elements.map(function (elem) {
return elem.getInnerHtml();
});
promise.all(pendingHtml).then(function (allHtml) {
// `allHtml` will be an `Array` of strings
});
});
这篇关于从findElement(By.className())获取元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!