从findElement(By.className())获取元素数组 [英] get an array of elements from findElement(By.className())

查看:561
本文介绍了从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
}

推荐答案

要检索多个元素的html,可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆